1、使用Microsoft.Build
进行项目编译
static void Build()
{
// 项目文件路径
string projectFilePath = @"C:\Users\97460\source\repos\ConsoleApp1\ConsoleApp1\ConsoleApp1.csproj";
// 方式1
Project project = new Project(projectFilePath);
if (project.Build())
{
Console.WriteLine("编译成功!");
}
else
{
Console.WriteLine("编译失败");
}
// 方式2
using (ProjectCollection projectCollection = new ProjectCollection())
{
// 编译结果日志输出文件
string buildResultFilePath = @"logfile=C:\\1.txt";
ILogger logger = new Microsoft.Build.Logging.FileLogger()
{
Parameters = buildResultFilePath,
};
// 编译全局全量
var globalProperty = new Dictionary<string, string>();
globalProperty.Add("Configuration", "Debug");
globalProperty.Add("Platform", "AnyCPU");
// 编译
var buidlRequest = new BuildRequestData(projectFilePath, globalProperty, null, new string[] { "Build" }, null);
var buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection)
{
Loggers = new Collection<ILogger> { logger }
},buidlRequest);
if (buildResult.OverallResult == BuildResultCode.Success)
{
Console.WriteLine("编译成功!");
}
else
{
Console.WriteLine("编译失败");
}
}
}
2、使用devenv命令行进行编译
static void BuildCmd()
{
// 添加devenv环境变量
string vs2022 = "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\";
var envirPaths = Environment.GetEnvironmentVariable("Path").Split(';');
if (envirPaths.FirstOrDefault(e => e == vs2022) == null)
{
var newPath = $"{Environment.GetEnvironmentVariable("Path")};{vs2022}";
Environment.SetEnvironmentVariable("Path", newPath);
}
// 项目文件路径
string solutionFilePath = "C:\\Users\\97460\\source\\repos\\ConsoleApp1\\ConsoleApp1.sln";
string projectFilePath = @"C:\Users\97460\source\repos\ConsoleApp1\ConsoleApp1\ConsoleApp1.csproj";
// 启动编译命令
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(solutionFilePath);
process.StartInfo.FileName = "cmd.exe";
// 编译解决方案(Debug编译)
process.StartInfo.Arguments = "/c " + $"devenv {solutionFilePath} /Build Debug";
// 编译项目(Release编译)
process.StartInfo.Arguments = "/c " + $"devenv {solutionFilePath} /Project {projectFilePath} /Build Release";
process.StartInfo.RedirectStandardOutput = true;
process.Start();
var buildResultInfo = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
Console.WriteLine(buildResultInfo);
}
更多的devenv
命令可阅读 Devenv 命令行开关 - Visual Studio (Windows) | Microsoft Learn