无法让 Roslyn 编译的可执行文件正常工作

Can't get Roslyn compiled executable working

提问人:szajch 提问时间:11/10/2023 最后编辑:szajch 更新时间:11/10/2023 访问量:29

问:

我正在使用 Visual Studio 和 Roslyn(以编程方式)编译此代码。 这是 .NET 6.0 代码。

    using System;
    
    namespace test
    {
        internal static class Program
        {
            static void Main()
            {
                Console.WriteLine("Test");
                Console.ReadKey(true);
            }
        }
    }

当我使用 Visual Studio 编译它时,代码正在工作。控制台正在写入“测试”输出。 但是当我用 Roslyn 编译它时,程序会编译,但是当我启动程序时会发生错误。 错误: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.

罗斯林代码:

                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");
                    }
                }
. NET-6.0 罗斯林

评论

0赞 Jason Malinowski 11/10/2023
输出类型为“WindowsApplication”,因此不会创建任何控制台。如果手动运行可执行文件,它是否仍在运行?你能在调试器下运行它吗?
0赞 Jason Malinowski 11/10/2023
另请注意,如果你正在尝试为 .NET 6 构建可执行文件,那么故事还有更多内容 - 在这种情况下,实际.exe不一定是由 Roslyn 生成的。
0赞 szajch 11/10/2023
@JasonMalinowski好的,我更新了 Roslyn。现在,当我启动程序时,控制台启动,但出现错误。

答: 暂无答案