Msbuild - how to delete folder contents but not folder itself?

Download and install the msbuild extension pack then use

<MSBuild.ExtensionPack.FileSystem.Folder TaskAction="RemoveContent" Path="$(Bin)" />

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 *

Tags:

Msbuild