我正在尝试编译此 C# 代码:
using System;
namespace test
{
internal static class Program
{
static void Main()
{
Console.WriteLine("Test");
Console.ReadKey(true);
}
}
}
使用 Roslyn 转换为单个 .exe 文件:
var syntaxTree = CSharpSyntaxTree.ParseText(source);
var compilation = CSharpCompilation.Create("program.exe")
.WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
.AddReferences(Net60.References.All)
.AddSyntaxTrees(syntaxTree);
EmitResult emitResult = compilation.Emit(Path.Combine(path, "program.exe"));
if (emitResult.Success)
{
MessageBox.Show("Compiled.");
}
else
{
MessageBox.Show($"The compiler has encountered {emitResult.Diagnostics.Length} errors", "Errors while compiling");
foreach (var diagnostic in emitResult.Diagnostics)
{
MessageBox.Show($"{diagnostic.GetMessage()}\nLine: {diagnostic.Location.GetLineSpan().StartLinePosition.Line} - Column: {diagnostic.Location.GetLineSpan().StartLinePosition.Character}", "Error");
}
}
编译时没有任何错误。它编译“正确”,但是当我启动它时,控制台中会弹出此错误:
Unhandled exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The specified file could not be found.
通过 Visual Studio 编译(生成 .exe 和 .dll)时,它可以工作。
我怎样才能让它工作?我只需要将其编译为一个单一的 .exe 文件。这可能吗?
罗斯林则不然; .NET SDK 支持将事物组合成单个可执行文件,但这是作为发布的一部分完成的,而不是 Roslyn 直接做的事情。要记住的一件事是,Roslyn 只是这里更大的工具链的一部分。