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?

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

2 Answers2

31

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 *
James Woolfenden
  • 6,498
  • 33
  • 53
  • 1
    Good answer. Also, use somthing like $(SolutionDir)\TestResults since GetDirectories requires an absolute path and this will make it relative to a solution. –  May 13 '19 at 03:39
9

Download and install the msbuild extension pack then use

<MSBuild.ExtensionPack.FileSystem.Folder TaskAction="RemoveContent" Path="$(Bin)" />
Ben C
  • 3
  • 2
Lazer89
  • 114
  • 2
  • What's the extension pack? Do I have to install it on all my colleagues' computers and all the build servers? – Colonel Panic Nov 04 '13 at 14:27
  • @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. – labilbe Aug 11 '16 at 11:01
  • 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 pack – BitSchupser Aug 16 '17 at 09:50