I want to compile a target project programmatically by using
Microsoft.Build.Evaluation.Project.Build()
If my target project that needs to be compiled contains C# 6.0 features like the safe navigation operator (?. Operator) it gives errors exactly on these lines of code.
If I remove these lines of code in my target project it compiles fine.
Does anyone have any idea how to compile C# 6.0 and 7.0 style code programmatically?
In the project that builds my runtime version of the build Microsoft.Build.dll is v4.0.30319 and the .Net framework version is 4.6.2.
I added two simple projects. The first console project is the code that compiles. The second console project is the target project to be compiled. By commenting out line 15, the compilation successful, otherwise the logfile shows errors on that line.
The project that compiles
using System;
using Microsoft.Build.Logging;
namespace CompilerApp
{
class Program
{
static void Main(string[] args)
{
string projectfile = @"C:\temp\CompilerApp\MyCSharp7\MyCSharp7.csproj";
UnloadAnyProject();
Microsoft.Build.Evaluation.Project p = new Microsoft.Build.Evaluation.Project(projectfile);
FileLogger loggerfile2 = new FileLogger();
loggerfile2.Parameters = @"logfile=C:\temp\CompilerApp\myapp.msbuild.log";
bool buildresult = p.Build(loggerfile2);
if (buildresult)
{
Console.WriteLine("project compiled");
}
else
{
Console.WriteLine("project not compiled, check {0}", @"C:\temp\myapp.msbuild.log");
}
p.Save();
UnloadAnyProject();
}
private static void UnloadAnyProject()
{
Microsoft.Build.Evaluation.ProjectCollection projcoll = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection;
foreach (Microsoft.Build.Evaluation.Project pr in projcoll.LoadedProjects)
{
Microsoft.Build.Evaluation.ProjectCollection mypcollection = pr.ProjectCollection;
mypcollection.UnloadProject(pr);
}
}
}
}
The targetproject that should be compiled:
using System;
namespace MyCSharp7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("truncate {0}", Truncate("Hello", 3));
}
public static string Truncate(string value, int length)
{
//csharp 6/7
//comment out line below for succesfull compilation
return value?.Substring(0, Math.Min(value.Length, length));
// csharp<6
string result = value;
if (value != null) // Skip empty string check for elucidation
{
result = value.Substring(0, Math.Min(value.Length, length));
}
return result;
}
}
}
Microsoft.Buildfrom NuGet?