翼度科技»论坛 编程开发 .net 查看内容

重建sln的项目层级

1

主题

1

帖子

3

积分

新手上路

Rank: 1

积分
3
编写包含多个 csproj 的程序时,随着项目数量的持续增加,可能涉及一些文件夹的变动,手动添加项目或者变动会变得非常麻烦,这个时候,可以利用 dotnet cli 帮助我们完成。
如果从零开始,我们可以新建一个解决方案。
  1. dotnet new sln -n todo.sln
复制代码
然后添加当前目录内的所有 csproj 文件到解决方案。
  1. $rootDir = Get-Location
  2. $solutionFile = "$rootDir\todo.sln"
  3. Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
  4.     $projectFile = $_.FullName
  5.     $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("")
  6.     $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
  7.     dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
  8. }
复制代码
这样生成的项目会保留每一个文件夹结构(解决方案文件夹),与 Visual Studio 的默认行为不同(会忽略与项目同名的解决方案文件夹创建)。
其实简单一些,直接使用这个命令就可以了:
  1. dotnet sln todo.sln add (ls -r **/*.csproj)
复制代码
这个命令等效于:
  1. $rootDir = Get-Location
  2. $solutionFile = "$rootDir\todo.sln"
  3. Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
  4.     $projectFile = $_.FullName
  5.     $parentDirectoryName = Split-Path $_.DirectoryName -Leaf
  6.     if ($_.Name -eq "$parentDirectoryName.csproj") {
  7.         if($_.DirectoryName -ne $rootDir){
  8.             $parentSolutionFolder = (Split-Path $_.DirectoryName -Parent).Replace($rootDir, "").TrimStart("")
  9.             $solutionFolder = if ($parentSolutionFolder) { "\$parentSolutionFolder" } else { "" }
  10.         }
  11.         else{
  12.             $solutionFolder = ""
  13.         }
  14.     } else {
  15.         $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("")
  16.         $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
  17.     }
  18.     dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
  19. }
复制代码
上面这个感觉很复杂,不过相当于给出了每一个步骤,如果后期有其他需求,可以在上面代码的基础上进行调整与改进。

来源:https://www.cnblogs.com/podolski/archive/2023/05/30/17443103.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具