I am trying to use Roslyn to compile DLL library. I tried various alternatives from How to compile a C# file with Roslyn programmatically? , let's say this one:
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
namespace SharedLibCompile
{
class Program
{
static void Main()
{
string sourceCode = File.ReadAllText(@"c:\Temp\SharedLib.cs");
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceCode));
CSharpCompilation compilation = CSharpCompilation
.Create("SharedLib.dll")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddSyntaxTrees(syntaxTree);
EmitResult result = compilation.Emit(@"c:\Temp\SharedLib.dll");
if (!result.Success)
Console.Out.WriteLine(string.Join(Environment.NewLine, result.Diagnostics.Select(diagnostic => diagnostic.ToString())));
}
}
}
Here is SharedLib.cs code:
using System;
namespace MyScript
{
public class SharedLib
{
public static string GetGreeting()
{
return "Ahoy";
}
}
}
Dll compiles successfully, it could be also included into solution and compiled:
using System;
using MyScript;
namespace IncludeSharedLib
{
class Program
{
static void Main()
{
Console.Out.WriteLine(SharedLib.GetGreeting());
}
}
}
However if I try to use it in executable, I got error
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'SharedLib.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. at IncludeSharedLib.Program.Main(String[] args)
The error is there despite SharedLib.dll is in the same folder as IncludeSharedLib.exe. I tried to check the Dll with DotPeek and it looks good. What do I do wrong?
I use .Net Framework 4.8 in both solutions and the latest Microsoft.CodeAnalysis.CSharp NuGet package.