Wednesday, September 16, 2015

Add Generated Files to your Project

I recently had to work with a small code generator and needed to dynamically add generated cs files to my csproj. This actually ended up being very simple!

You will need to use ProjectCollection in the Microsoft.Build assembly to load the project, and then once you have scanned the directory for files you can easily diff the two to find new files. The only "catch" is that you need be sure to match the files to the relative paths from the csproj.

Code

Here is a very simple sample console application that adds generated files to another csproj. (See the picture to the right for the exact file structure.)

public static void Main()
{
    const string relativePath = "../../../TestProj/";
 
    var files = Directory
        .GetFiles(relativePath + "Generated", "*.cs")
        .Select(r => r.Replace(relativePath, string.Empty));
 
    using (var engine = new ProjectCollection())
    {
        var project = engine.LoadProject(relativePath + "TestProj.csproj");
 
        var newFiles = files
            .Where(f => !project.Items.Any(i => i.UnevaluatedInclude == f))
            .ToList();
 
        foreach (var newFile in newFiles)
        {
            project.AddItem("Compile", newFile);
        }
 
        project.Save();
    }
}

Enjoy,
Tom

1 comment:

  1. Awesome. So simple.
    A lot easier than using [EnvDTE80.Solution2]. Had done that with powershell few weeks back to automate some things when installing a nuget package.

    ReplyDelete

Real Time Web Analytics