'How to programmatically compile .net core 3.1 application?
Is there a way to compile a WebAPI app from console app in .NET Core 3.1?
I have tried many different approaches, such as:
1.
var collection = ProjectCollection.GlobalProjectCollection;
var project = collection.LoadProject($@"{path}\Project.csproj");
project.SetProperty("Configuration", configuration);
project.Build();
(Path to .sln)
ERROR: MSB4041: The default XML namespace of the project must be the MSBuild XML namespace.
2.
new Microsoft.Build.Execution.ProjectInstance("PathToProject.sln").Build();
(Path to .sln)
ERROR: Microsoft.Build.Exceptions.InvalidProjectFileException: 'The project file could not be loaded. Data at the root level is invalid.
(Path to .csproj)
ERROR: Microsoft.Build.Exceptions.InvalidProjectFileException: 'The SDK 'Microsoft.NET.Sdk.Web' specified could not be found.
3.
ProjectCollection pc = new ProjectCollection();
Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();
GlobalProperty.Add("Configuration", "Debug");
GlobalProperty.Add("Platform", "Any CPU");
GlobalProperty.Add("OutputPath", Directory.GetCurrentDirectory() + "\\MyOutput");
BuildParameters bp = new BuildParameters(pc);
BuildManager.DefaultBuildManager.BeginBuild(bp);
BuildRequestData BuildRequest = new BuildRequestData(projectFilePath, GlobalProperty, null, new string[] { "Build" }, null);
BuildSubmission BuildSubmission = BuildManager.DefaultBuildManager.PendBuildRequest(BuildRequest);
BuildSubmission.Execute();
BuildManager.DefaultBuildManager.EndBuild();
if (BuildSubmission.BuildResult.OverallResult == BuildResultCode.Failure)
{
throw new Exception();
}
(Both path to .sln and .csproj)
ERROR: Build result is a failure without reported exception
However, none of the approaches worked. Therefore, I am wondering is it even possible to compile the .NET Core 3.1 WebAPI code?
Solution 1:[1]
The only way I could get this to work was to use the following code snippet (.NET 6):
var commandText = $"myProject.csproj";
p.StartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\msbuild.exe", commandText);
p.StartInfo.WorkingDirectory = projectFileLocation;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
while (!p.StandardOutput.EndOfStream)
{
var line = p.StandardOutput.ReadLine();
sb.Append(line);
}
p.WaitForExit();
I hope this saves somebody a lot more time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Ehnis |
