重建sln的项目层级
编写包含多个 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
}
上面这个感觉很复杂,不过相当于给出了每一个步骤,如果后期有其他需求,可以在上面代码的基础上进行调整与改进。
本文作者:波多尔斯基
本文链接:https://www.cnblogs.com/podolski/p/17443103.html
版权声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步