Pre Build Events and the Before Build Target

September 25, 2007

Its quite common to use pre and post build events in your c# projects. You enter the command you want to run in the project properties, like below.

Prebuild event

But this isn’t the only way to achieve this. There is another way by editing your .csproj file and using the BeforeBuild target. 

First lets look how the PreBuildEvent from the project properties is actually handled. At the bottom of your project file you’ll find a property that lists your command. 

<PropertyGroup> 
  <PreBuildEvent>copy $(OutDir)\test.blah c:\test</PreBuildEvent> 
</PropertyGroup>

If you follow your imports in your project file you’ll find that your PreBuildEvent is handled by the PreBuildEvent target in Microsoft.Common.Targets. What does this do? It calls the Exec task on your command, which runs in as any other command prompt command.

<Target 
    Name="PreBuildEvent" 
    Condition="'$(PreBuildEvent)'!=''" 
    DependsOnTargets="$(PreBuildEventDependsOn)">
    <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
</Target>

In your .csproj file you will find out two targets (BeforeBuild and AfterBuild) that have been commented out. The other way is to uncomment these and add msbuild tasks. These targets are called exactly when their name suggests.

<Target Name="BeforeBuild"> 
</Target>

If we want to copy a file then we can use the Copy task

<Target Name="BeforeBuild"> 
       <Copy SourceFiles="c:\test.txt" DestinationFolder="d:\dest\"/> 
</Target>

No command line, no batch files. Just pure msbuild

One Response to “Pre Build Events and the Before Build Target”

  1. dan Says:

    thanks mate that helped me heaps!


Leave a comment