Automated compilation of Visual Studio Projects through C# using MSBuild

January 19th, 2011 by Dinesh 1 comment »

Automated compilation of Visual Studio project is a feature of many project management tools.  The same could be done easily through C# as well. We can use the MSBuild tool to accomplish this.

You need to make a reference to Microsoft.Build.Engine. We also need a file logger class to record the outputs thrown by the MSBuild while compiling.

Output of the C# program while compiling solution “Web1”,

Actual error listing made by Visual Studio on the while compiling solution “Web1”,

Here just shown the output first, don’t get confused. Find the code below,

C# code for MSBuild:

The solution builder class which is the core of this application is as follows,

using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;public class SolutionBuilder
{
BasicFileLogger b;
public SolutionBuilder() { }

[STAThread]
public string Compile(string solution_name,string logfile)
{
b = new BasicFileLogger();

b.Parameters = logfile;

b.register();

Microsoft.Build.BuildEngine.Engine.GlobalEngine.BuildEnabled = true;

Project p = new Project (Microsoft.Build.BuildEngine.Engine.GlobalEngine);

p.BuildEnabled = true;

p.Load(solution_name);

p.Build();

string output = b.getLogoutput();

output += “\n\t” + b.Warningcount + ” Warnings. “;
output += “\n\t” + b.Errorcount + ” Errors. “;

b.Shutdown();

return output;
}
}

The above class is used and compilation is initiated by the following code,

static void Main(string[] args)
{
SolutionBuilder builder = new SolutionBuilder();string output = builder.Compile(@”G:\Codes\Testing\Testing2\web1.sln”, @”G:\Codes\Testing\Testing2\build_log.txt”);

Console.WriteLine(output);

Console.ReadKey();

}

About the code:
Apart from these two codes, one more to be noticed is “BasicFileLogger” class which is used for the logging operations. This code is available in MSDN. You can also download from here: BasicFileLogger.cs

This code worked for the properly created solutions. You can refer the way my previous post, creating a blank solution. It is built and compiled using Microsoft Visual C# 2008. It works successfully in compiling a Visual Studio solutions.

I hope this would be helpful to build a system to build .NET projects.