5

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.

Joe SHI
  • 1,734
  • 4
  • 20
  • 39

3 Answers3

3

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();
csblo
  • 1,571
  • 13
  • 20
  • collection.LoadProject give error "Microsoft.Build.Exceptions.InvalidProjectFileException: 'The tools version "14.0" is unrecognized. Available tools versions are "4.0". C:\Users\User\Documents\Projects\practice\wpf\WPF-Samples-netframework\Graphics\2DTransforms\2DTransforms.csproj'" – Chaya Mar 08 '23 at 06:32
1

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

Dejas
  • 3,511
  • 4
  • 24
  • 36
  • This link is no longer good. It just goes to the top of the blog stack, which only goes back to 2020. I recommend replacing it with https://learn.microsoft.com/en-us/troubleshoot/dotnet/csharp/compile-code-using-compiler. The edit queue is full, so I can't suggest that as an edit. – Jamie Jun 24 '21 at 16:14
-1

Assuming you're using Visual Studio you could just use run MSBuild against your ProjectB.csproj. That way you project should build identical to how it would build in Visual Studio.

AVee
  • 3,348
  • 17
  • 17