Msbuild - how to delete folder contents but not folder itself?
Asked Answered
T

2

15

Right now in my msbuild script is a task to delete a folder

<RemoveDir Directories="$(Bin)"/>

However I'd rather delete the contents of the folder but leave the folder be (in case someone has the folder open in Windows Explorer). How can I do that?

Thiele answered 27/2, 2013 at 10:31 Comment(0)
M
9

Download and install the msbuild extension pack then use

<MSBuild.ExtensionPack.FileSystem.Folder TaskAction="RemoveContent" Path="$(Bin)" />
Mainstay answered 22/4, 2013 at 16:47 Comment(3)
What's the extension pack? Do I have to install it on all my colleagues' computers and all the build servers?Thiele
@ColonelPanic It's a collection of useful MSBuild tasks maintained by Mike Fourie (not Microsoft). You can install it, but I prefer to add it to my repository so the build can be done even if MSBuild tasks are not installed on the build machine.Whetstone
You can also add the extensions pack via nuget. Then you'll have it at the repository and the nuget installer automatically configures the csproj file to reference the extensions packForeglimpse
T
32

This will remove all files and subfolders:

    <Target Name="CleanFolder">

    <PropertyGroup>
      <TargetFolder>c:\clean</TargetFolder>
    </PropertyGroup>

    <ItemGroup>
      <FilesToClean Include="$(TargetFolder)\**\*"/>
      <Directories Include="$([System.IO.Directory]::GetDirectories('$(TargetFolder)', '*', System.IO.SearchOption.AllDirectories))"
                   Exclude="$(TargetFolder)"/>
    </ItemGroup>

    <Delete Files="@(FilesToClean)" ContinueOnError="true"/>
    <RemoveDir Directories="@(Directories)" />
  </Target>

It would also be good to drop open connections using the openfiles tool:

openfiles /disconnect /ID *
Tierratiersten answered 27/2, 2013 at 13:35 Comment(1)
Good answer. Also, use somthing like <TargetFolder>$(SolutionDir)\TestResults</TargetFolder> since GetDirectories requires an absolute path and this will make it relative to a solution.Feudal
M
9

Download and install the msbuild extension pack then use

<MSBuild.ExtensionPack.FileSystem.Folder TaskAction="RemoveContent" Path="$(Bin)" />
Mainstay answered 22/4, 2013 at 16:47 Comment(3)
What's the extension pack? Do I have to install it on all my colleagues' computers and all the build servers?Thiele
@ColonelPanic It's a collection of useful MSBuild tasks maintained by Mike Fourie (not Microsoft). You can install it, but I prefer to add it to my repository so the build can be done even if MSBuild tasks are not installed on the build machine.Whetstone
You can also add the extensions pack via nuget. Then you'll have it at the repository and the nuget installer automatically configures the csproj file to reference the extensions packForeglimpse

© 2022 - 2024 — McMap. All rights reserved.