I am wondering if there is a way to pass command line arguments to roslyn when compiling and executing code.
My current code for generating a compiler and executing source code looks like this:
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;
}
}
The goal is to have some sort of source code like this:
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);
}
}
Where I can pass a command-line argument in and get the result of Console.WriteLine(). What would be the best way to handle this? The current code does build and will compile and analyze source code.
The code would be written in a .NET core 3.1 mvc web app.