Reputation: 2105
I have a project in c# that I would like to compile programmatically and put it in Release folder.
I am using CodeDomProvider, here below is my code:
class Compiler
{
public static void Build(string filename,string outputAssemblyPath)
{
CodeDomProvider cdp = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cp = new CompilerParameters()
{
GenerateExecutable = true,
GenerateInMemory = true,
IncludeDebugInformation = true,
OutputAssembly = outputAssemblyPath
};
CompilerResults result = cdp.CompileAssemblyFromFile(cp, filename);
foreach (string s in result.Output)
{
Console.WriteLine(s);
}
}
}
I am calling Build method the following way:
class Program
{
static void Main(string[] args)
{
Compiler.Build("C:/Projects/Project1/alan.project/Project1.csproj", "C:/Projects/Project1/alan.project/bin/Release/");
Console.ReadLine();
}
}
All I want to do is instead of clicking "Rebuild" and have my project compiled in the Release directory, I want it done programmatically.
Upvotes: 0
Views: 2082
Reputation: 895
One of decision it's using MSBuild SDK
, that allows create custom task on C#
. Through it you can controll build process, describe own logic.
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Linq;
namespace MSBuild.Common
{
class Build : Task
{
[Required]
public string Solution
{
get;
set;
}
public override bool Execute()
{
return BuildEngine2.BuildProjectFilesInParallel(SolutionFile.Parse(Solution).ProjectsByGuid.Select(p => p.Value.AbsolutePath).ToArray(), null, null, null, null, true, false);
}
}
}
This is task example. It's accept path to the solution and perform parallel compile its projects. You can add properties to BuildProjectFilesInParallel that will describe build process.
Call of created task will be from the custom target:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" InitialTargets="EntryBuild">
<UsingTask AssemblyFile="Build.dll" TaskName="Build" />
<Target Name="EntryBuild">
<Build Solution="$(Solution)" />
</Target>
</Project>
Execute it through MSBuild CLI
:
msbuild.exe /t:Build.targets /p:Solutin=%pathToSolution%
MSBuild Targets | Task Writing
Upvotes: 2