简体   繁体   English

如何以编程方式从当前项目中构建和编译另一个c#项目

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

Program A: output ac# function, and insert the function into a file (eg. Classifier.cs) in another c# project B. These steps have already been implemented. 程序A:输出ac#函数,并将该函数插入到另一个c#项目B中的文件(例如,Classifier.cs)中。这些步骤已经实现。

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. 我想知道有没有办法以编程方式在项目A中编译和编译c#项目B.所以我可以单击项目A中的一个按钮,它会自动将新函数插入项目B,构建,编译项目B.最后启动新项目B.

Thank you. 谢谢。

There are a lot of compilation assemblies for .NET that are now obsoletes. .NET有很多编译程序集,现在已经过时了。 For compilation, use Microsoft.Build. 要进行编译,请使用Microsoft.Build。

First, Add this following references : 首先,添加以下参考:

  • Microsoft.Build Microsoft.Build
  • Microsoft.Build.Engine 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();

No need to execute a new process. 无需执行新流程。 .NET gives us a way to invoke the C# compiler programatically. .NET为我们提供了一种以编程方式调用C#编译器的方法。 I find this technique works well: 我发现这种技术效果很好:

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

Assuming you're using Visual Studio you could just use run MSBuild against your ProjectB.csproj. 假设您使用的是Visual Studio,则可以对ProjectB.csproj使用运行MSBuild。 That way you project should build identical to how it would build in Visual Studio. 这样你的项目应该与它在Visual Studio中构建的方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM