Tuesday, March 23, 2010

MSBuild - Cleaning a folder

It is a common need to clean the destination folder (deleting all files and folders) when you automate your deployment builds. Unfortunately, MSBuild does not have a built-in task that does it all for you, and googling about it does not give you a clear answer.

It is however pretty easy to do by combining the Delete and RemoveDir tasks together. Below is a code snippet that does it.

The code should be self-explanatory enough with the few comments.


<Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <!-- Folder to clean - Trailing slash required -->
        <DeleteRoot>D:\Test\Deploy\</DeleteRoot>
    </PropertyGroup>
    <Target Name="Default">
        <ItemGroup>
            <!-- Item to get all files recursively in the DeleteRoot folder -->
            <FilesToDelete Include="$(DeleteRoot)\**\*.*" />
            <!-- Item to get all folders from the files to be deleted -->
            <FoldersToDelete Include="%(FilesToDelete.RootDir)%(FilesToDelete.Directory)" Exclude="$(DeleteRoot)"/>
        </ItemGroup>
        <!-- Display what will be deleted -->
        <Message Text=" # @(FilesToDelete)" Importance="normal" />
        <Message Text=" # @(FoldersToDelete)" Importance="normal" />
        <!-- Delete the files -->
        <Delete Files="@(FilesToDelete)" Condition=" $(DeleteRoot)!=''" /> 
        <!-- Remove the folders -->
        <RemoveDir Directories="@(FoldersToDelete)" Condition="$(DeleteRoot)!=''" />
    </Target>
</Project>

2 comments:

Martin Lundhgren said...

Very good! Helped me alot, thank you!

Julien Jacobs said...

Glad it helped you! Thank you for letting me know :-)