重建sln的项目层级

发布时间 2023-05-30 14:21:52作者: 波多尔斯基

编写包含多个 csproj 的程序时,随着项目数量的持续增加,可能涉及一些文件夹的变动,手动添加项目或者变动会变得非常麻烦,这个时候,可以利用 dotnet cli 帮助我们完成。

如果从零开始,我们可以新建一个解决方案。

dotnet new sln -n todo.sln

然后添加当前目录内的所有 csproj 文件到解决方案。

$rootDir = Get-Location
$solutionFile = "$rootDir\todo.sln"

Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
    $projectFile = $_.FullName
    $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("\")
    $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
    dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
}

这样生成的项目会保留每一个文件夹结构(解决方案文件夹),与 Visual Studio 的默认行为不同(会忽略与项目同名的解决方案文件夹创建)。

其实简单一些,直接使用这个命令就可以了:

dotnet sln todo.sln add (ls -r **/*.csproj)

这个命令等效于:

$rootDir = Get-Location
$solutionFile = "$rootDir\todo.sln"

Get-ChildItem -Recurse -Filter *.csproj | ForEach-Object {
    $projectFile = $_.FullName
    $parentDirectoryName = Split-Path $_.DirectoryName -Leaf
    if ($_.Name -eq "$parentDirectoryName.csproj") {
        if($_.DirectoryName -ne $rootDir){
            $parentSolutionFolder = (Split-Path $_.DirectoryName -Parent).Replace($rootDir, "").TrimStart("\")
            $solutionFolder = if ($parentSolutionFolder) { "\$parentSolutionFolder" } else { "" }
        }
        else{
            $solutionFolder = ""
        }
    } else {
        $relativePath = $_.DirectoryName.Replace($rootDir, "").TrimStart("\")
        $solutionFolder = if ($relativePath) { "\$relativePath" } else { "" }
    }
    dotnet sln $solutionFile add $projectFile --solution-folder $solutionFolder
}

上面这个感觉很复杂,不过相当于给出了每一个步骤,如果后期有其他需求,可以在上面代码的基础上进行调整与改进。