Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically build and compile another c# project from the current project

Tags:

c#

Program A: output a c# function, and insert the function into a file (eg. Classifier.cs) in another c# project B. These steps have already been implemented.

I am wondering is there any way to programmatically build and compile the the c# project B inside project A. So I can click a button in project A, it will automatically insert the new function into project B, build, compile the project B. And finally launch the new project B.

Thank you.

like image 326
Joe SHI Avatar asked Nov 04 '22 09:11

Joe SHI


2 Answers

There are a lot of compilation assemblies for .NET that are now obsoletes. For compilation, use Microsoft.Build.

First, Add this following references :

  • Microsoft.Build
  • Microsoft.Build.Engine

Secondly, import :

using Microsoft.Build.Evaluation;

And finally, write this code :

var configuration = "Release";
var projectDirectory = @"C:\blabla";
var collection = ProjectCollection.GlobalProjectCollection;
var project = collection.LoadProject($@"{projectDirectory}\MyProject.csproj");
project.SetProperty("Configuration", configuration);

project.Build();
like image 161
csblo Avatar answered Nov 14 '22 14:11

csblo


No need to execute a new process. .NET gives us a way to invoke the C# compiler programatically. I find this technique works well:

http://blogs.msdn.com/b/dohollan/archive/2010/08/09/programmatically-invoke-the-c-compiler.aspx

like image 31
Dejas Avatar answered Nov 14 '22 13:11

Dejas