I'm trying to compile an assembly using CSharpCompilation
that has a simple class in it, that I can then reference in another program that is also compiled through CSharpCompilation
. I have this code:
namespace CompilationTest { class Program { static void Main(string[] args) { HashSet<Assembly> referencedAssemblies = new HashSet<Assembly>() { typeof(object).Assembly, Assembly.Load(new AssemblyName("Microsoft.CSharp")), Assembly.Load(new AssemblyName("netstandard")), Assembly.Load(new AssemblyName("System.Runtime")), Assembly.Load(new AssemblyName("System.Linq")), Assembly.Load(new AssemblyName("System.Linq.Expressions")) }; string greetingClass = @" namespace TestLibraryAssembly { public static class Greeting { public static string GetGreeting(string name) { return ""Hello, "" + name + ""!""; } } } "; CSharpCompilation compilation1 = CSharpCompilation.Create( "TestLibraryAssembly", new [] { CSharpSyntaxTree.ParseText(greetingClass) }, referencedAssemblies.Select(assembly => MetadataReference.CreateFromFile(assembly.Location)).ToList(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); MemoryStream memoryStream1 = new MemoryStream(); EmitResult emitResult1 = compilation1.Emit(memoryStream1); memoryStream1.Position = 0; MetadataReference testLibraryReference = MetadataReference.CreateFromStream(memoryStream1); string programCode = @" using TestLibraryAssembly; namespace TestProgram { public class Program { public void Main() { string greeting = Greeting.GetGreeting(""Name""); } } } "; CSharpCompilation compilation2 = CSharpCompilation.Create( "TestProgram", new [] { CSharpSyntaxTree.ParseText(programCode) }, referencedAssemblies .Select(assembly => MetadataReference.CreateFromFile(assembly.Location)) .Concat(new List<MetadataReference> { testLibraryReference }).ToList(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); MemoryStream memoryStream2 = new MemoryStream(); EmitResult emitResult2 = compilation2.Emit(memoryStream2); memoryStream2.Position = 0; Assembly programAssembly = Assembly.Load(memoryStream2.ToArray()); Type programType = programAssembly.GetType("TestProgram.Program"); MethodInfo method = programType.GetMethod("Main"); object instance = Activator.CreateInstance(programType); method.Invoke(instance, null); } } }
However, when I run this, I get this error:
Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.IO.FileNotFoundException: Could not load file or assembly 'TestLibraryAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'TestLibraryAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
How can I fix this error?