将命令行参数传递给roslyn编译器

时间:2020-10-25 22:01:13

标签: c# .net-core roslyn roslyn-code-analysis

我想知道在编译和执行代码时是否有一种方法可以将命令行参数传递给roslyn。

我当前用于生成编译器和执行源代码的代码如下:

CSharpCompilation compilation = CSharpCompilation.Create(Path.GetFileName(assemblyPath))
  .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
  .AddReferences(references)
  .AddSyntaxTrees(syntaxTree);

using (var memStream = new MemoryStream())
{
  var result = compilation.Emit(memStream);
  if (!result.Success)
  {
    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
        diagnostic.IsWarningAsError ||
        diagnostic.Severity == DiagnosticSeverity.Error);

    foreach (Diagnostic diagnostic in failures)
    {
        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
    }
  }
  else
  {
    memStream.Seek(0, SeekOrigin.Begin);
    Assembly assembly = Assembly.Load(memStream.ToArray());
    var test = assembly;
  }
}

目标是拥有这样的某种源代码:

using System;

class Program
{
  static string StringToUppercase(string str)
  {
    return str.ToUppercase();
  }

  static void Main(string[] args)
  {
    string str = Console.ReadLine();
    string result = StringToUppercase(str);
    Console.WriteLine(result);
  }

}

我可以在其中传递命令行参数并获得Console.WriteLine()的结果。处理此问题的最佳方法是什么?当前的代码确实可以构建并将编译和分析源代码。

该代码将在.NET core 3.1 mvc Web应用程序中编写。

1 个答案:

答案 0 :(得分:0)

我猜您想将参数传递给已编译的应用程序,而不是roslyn :)
执行编译后的代码,并使用Console.SetOut(TextWriter)获取其输出(例如:sof link):

Assembly assembly = Assembly.Load(memStream.ToArray());
// Console.SetOut to a writer
var test = assembly.EntryPoint.Invoke(null, new object[] { "arg1", "arg2" });
// And restore it

或为其启动新的过程:

memStream.CopyTo(File.OpenWrite("temp.exe"))
// Copied from MSDN
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput
using (Process process = new Process())
{
    process.StartInfo.FileName = "temp.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();

    // Synchronously read the standard output of the spawned process.
    StreamReader reader = process.StandardOutput;
    string output = reader.ReadToEnd();

    // Write the redirected output to this application's window.
    Console.WriteLine(output);

    process.WaitForExit();
}
相关问题