如何解决将命令行参数传递给roslyn编译器
我想知道在编译和执行代码时是否有一种方法可以将命令行参数传递给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应用程序中编写。
解决方法
我猜您想将参数传递给已编译的应用程序,而不是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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。