2

I am new with Roslyn and I am trying to compile my first code at runtime.

The code compile(exe) without error but when i run it throught process.Start() in the concole output appers the error

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I read that many other people had same problem but the solution here : https://github.com/dotnet/core/issues/2082 not worked for me

This is the full code of my console app :

using System;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Extensions.DependencyModel;
using System.Linq;

namespace TestRoslyn
{
    class Program
    {

        static string code = @"
                                using System;
                                namespace First
                                {
                                    public class Program
                                    {
                                        public static void Main()
                                        {" +
                                            "Console.WriteLine(\"Hello, world!\");"
                                    + @"
                                        }
                                    }
                                }
                                ";

        static void Main(string[] args)
        {
            MetadataReference[] _ref = DependencyContext.Default.CompileLibraries
                           .SelectMany(cl => cl.ResolveReferencePaths())
                           .Select(asm => MetadataReference.CreateFromFile(asm))
                           .ToArray();

            var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code));
            var assemblyPath = Path.ChangeExtension(Path.GetTempFileName(), "exe");
            var compilation = CSharpCompilation.Create(Path.GetFileName(assemblyPath))
                .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                .AddReferences(_ref)
                .AddSyntaxTrees(syntaxTree);

            var result = compilation.Emit(assemblyPath);
            if (result.Success) // Compilation is Success
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = assemblyPath;
                    process.Start(); // Here the error appears in the console window
                }
            }
            else
            {
                System.Diagnostics.Debug.Write(string.Join(
                    Environment.NewLine,
                    result.Diagnostics.Select(diagnostic => diagnostic.ToString())
                ));
            }
        }
    }
}

project file

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.10.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="5.0.0" />
  </ItemGroup>

</Project>

Can someone help me ?

GLuca74
  • 105
  • 6
  • Change `System.Diagnostics.Debug.Write` to `Console.Write` – Luuk Jun 23 '21 at 16:37
  • I changed, but the problem is not in the app that generate the exe, the problem is in the generated exe. In the generated exe there is already `Console.Write` – GLuca74 Jun 23 '21 at 16:42
  • I did have a better look at the code, and while debugging, I did see the `_refs` remains empty. Maybe this question can help to solve it: https://stackoverflow.com/questions/32769630/how-to-compile-a-c-sharp-file-with-roslyn-programmatically (BTW: I am newer with Roslyn ) – Luuk Jun 23 '21 at 17:32
  • _refs remains empty if in the project file `true` is not added. Have you added it? – GLuca74 Jun 23 '21 at 17:54
  • That made a difference... But now I have same error as you have. When looking at the exe file (in the temp folder) with [ILSpy](https://ilspy.net/) I do see references to .NETCore 3.1, and not to .NetCore 5 – Luuk Jun 23 '21 at 19:25
  • With ILSpy : If i Publish a new empty console from visualstudio as portable, visual studio produce 1 exe and 1 dll, ILSpy can not load the exe but load the dll. If I publish as win-x64 same. If I add Produce single file ILSpy open the exe(it is the only produced) and inside has a depps.json, a runtimeconfig.json and the assembly. With my code Roslyn produces only one exe and ILSpy can not open it like the first and second test with ILSpy – GLuca74 Jun 23 '21 at 21:13
  • 1
    Have a look on my response on https://stackoverflow.com/questions/68109143/choose-references-dynamically-in-net-core-for-roslyn –  Jun 25 '21 at 19:35
  • Guy at Mercator, I also tryed your way to get the references but stil not works, because my problem seems it is not a references problem, I already get the reference assemblies. My problem seems related to I need to compile an EXE, all the examples regards compiling DLL. When the output is an EXE, there are different wasy to achive, I belive I have to check in deep this ways – GLuca74 Jun 29 '21 at 19:25

0 Answers0