Any way to edit .csproj file during package install?

Jun 6, 2011 at 11:33 PM

I am developing a nuget package, and when my package is installed, I would like it to add an "AfterBuild" build target to the .csproj file...something like this:

<Target Name="MyTarget" AfterTargets="Build">

<DoSomethingMyPackageRequires />


Is there currently a way to do this?

Jun 6, 2011 at 11:40 PM

You can only do this by adding some powershell script. Take a look at my NuGetPowerTools package:

Jun 6, 2011 at 11:43 PM

Exactly the type of example I was looking for.  Thanks for the quick response.

Jun 13, 2011 at 8:36 AM

I'm looking at these scripts but am a bit lost (I'm a newbie to powershell). Is there a really simple example somewhere of a powershell script that simply adds a BeforeBuild/AfterBuild step to a csproj file?

Jun 13, 2011 at 2:53 PM

Here is a really simple example of how to add an AfterBuild step:

$project = Get-Project
$buildProject = Get-MSBuildProject

$target = $buildProject.Xml.AddTarget("MyCustomAfterBuild")
$target.AfterTargets = "AfterBuild"
$task = $target.AddTask("Message")
$task.SetParameter("Text", "Hello AfterBuild")

$project.Save() #persists the changes

The Get-MSBuildProject command is part of David Fowler's NuGetPowertools linked above.  Its basically a helper for getting to the MSBuild object model.  I used reflector/object browser to figure out the API, but its actually pretty intuitive.  Its also documented here:
As far as the uninstall goes, I haven't figured that out yet.  I have an outstanding discussion post asking for help, but no one has responded.

Jun 13, 2011 at 3:06 PM

Thanks, I'll give this a try. (I also asked on StackOverflow, but so far no one has given any response. I'm considering writing a small C# app to modify the csproj, since I at least know what I'm doing in C#.

Jun 14, 2011 at 7:35 AM

@markheath: PowerShell is so powerful. Pick up a copy of, the best book on PowerShell, and go that route.

Jun 14, 2011 at 9:55 AM

thanks, I'd like to learn PowerShell properly in the not too distant future so I'll add that book to my list. It seems that everything I am trying to do at the moment requires me learning a whole new syntax (it took me a while to get to grips with MSBuild).

I've hit another roadblock anyway - my "BeforeBuild" step runs a custom task that modifies the AssemblyInfo.cs file to update the version number. However, despite it successfully updating AssemblyInfo.cs, the build always comes out with the version number before. Can't understand what is going on there, but until I get it working properly there is no point me creating the nuget package for it.