我与多个项目一起工作,我想递归删除所有名为“bin”或“obj”的文件夹,这样我就可以确保所有项目都会重新构建所有内容(有时这是迫使Visual Studio忘记所有以前的构建的唯一方法)。
是否有一种快速的方法来实现这一点(例如使用.bat文件),而不必编写。net程序?
我与多个项目一起工作,我想递归删除所有名为“bin”或“obj”的文件夹,这样我就可以确保所有项目都会重新构建所有内容(有时这是迫使Visual Studio忘记所有以前的构建的唯一方法)。
是否有一种快速的方法来实现这一点(例如使用.bat文件),而不必编写。net程序?
当前回答
在VS 2019/VS 2022中,这是唯一明智的解决方案。
在解决方案文件夹(.sln文件所在的位置)中,创建一个名为Directory.Build.props的文件,并按如下所示添加编辑它。在这里阅读这个特殊的文件。
Directory.Build.props
<Project>
<Target Name="RemoveObjAndBinFolders" AfterTargets="Clean">
<PropertyGroup>
<ObjFolder>$(ProjectDir)$(BaseIntermediateOutputPath)</ObjFolder>
<BinFolder>$(ProjectDir)$(BaseOutputPath)</BinFolder>
<!-- Microsoft.NET.Sdk.Web sets $(BaseIntermediateOutputPath) to -->
<!-- an absolute path. Not fixed up to MsBuild 17! -->
<BaseIntermediateOutputPathFix Condition="$(BaseIntermediateOutputPath.StartsWith($(MSBuildProjectDirectory)))">$([MSBuild]::MakeRelative(
$(ProjectDir),
$(BaseIntermediateOutputPath)
))</BaseIntermediateOutputPathFix>
<ObjFolder Condition="$(BaseIntermediateOutputPath.StartsWith($(MSBuildProjectDirectory)))">$(ProjectDir)$(BaseIntermediateOutputPathFix)</ObjFolder>
</PropertyGroup>
<ItemGroup>
<ObjFiles Include="$(ObjFolder)/*.*"
Exclude="$(ObjFolder)/project.assets.json" />
<ObjSubFolders
Include="$([System.IO.Directory]::GetDirectories('$(ObjFolder)'))" />
</ItemGroup>
<!-- Remove "obj" sub folders -->
<RemoveDir Directories="@(ObjSubFolders)" ContinueOnError="true" />
<!-- Remove "obj" files (keeping necessary asset file)-->
<Delete Files="@(ObjFiles)" />
<!-- Remove "bin" folders -->
<RemoveDir Directories="$(BinFolder)" ContinueOnError="true" />
</Target>
</Project>
不需要修改一堆.csproj文件。另外,请注意,我并没有像一些人建议的那样删除$(TargetDir)。如果$(OutDir)被设置为某个自定义目录(一种常见的做法),那么这样做可能会使构建系统瘫痪。
其他回答
实际上,你可以进一步使用PS的建议,在项目目录中创建一个vbs文件,就像这样:
Option Explicit
Dim oShell, appCmd
Set oShell = CreateObject("WScript.Shell")
appCmd = "powershell -noexit Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse -WhatIf }"
oShell.Run appCmd, 4, false
为了安全起见,我包含了-WhatIf参数,所以如果在第一次运行时对列表感到满意,可以删除它。
我认为你可以右键点击你的解决方案/项目,然后点击“清洁”按钮。
据我所知,它是这样工作的。我现在没有VS.NET,所以不能测试它。
这招对我很管用:
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
根据superuser.com上的答案
在添加到项目文件之前删除bin和obj:
<Target Name="BeforeBuild">
<!-- Remove obj folder -->
<RemoveDir Directories="$(BaseIntermediateOutputPath)" />
<!-- Remove bin folder -->
<RemoveDir Directories="$(BaseOutputPath)" />
</Target>
这是文章:如何删除bin和/或obj文件夹构建或部署之前
我讨厌obj文件乱扔源代码树。我通常设置项目,以便它们在源树外输出obj文件。对于我通常使用的c#项目
<IntermediateOutputPath>..\..\obj\$(AssemblyName)\$(Configuration)\</IntermediateOutputPath>
用于c++项目
IntermediateDirectory="..\..\obj\$(ProjectName)\$(ConfigurationName)"