3

I need to compile C# code at run-time. I'm using the code like this:

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("MyLibrary.dll");    // File Path on Hard Drive
...

But I want to use the libraries loaded on memory instead of their file addresses. Is it possible?

Jester
  • 56,577
  • 4
  • 81
  • 125
Ali Sepehri.Kh
  • 2,468
  • 2
  • 18
  • 27
  • 2
    This is a very persistent myth. "Loaded on memory" is an illusion, current compilers (csc.exe in your case) run out-of-process and read/write assemblies on disk. All that the GenerateInMemory property does is forcing a call to Assembly.LoadFrom(). So just don't bother. – Hans Passant Sep 02 '14 at 11:06

1 Answers1

3

If it is an assembly that isn't generated in-memory only, you could use:

parameters.ReferencedAssemblies.Add
( typeof(ClassInAssemblyYouWantToAdd).Assembly.Location
);

Or:

parameters.ReferencedAssemblies.Add
( Assembly.Load("Full.Qualified.Assembly.Name").Location
);

The Location property has the path to the assembly loaded.

It has to have a hard copy of the assembly, and not just something in memory, so you can't just use generated assemblies for that. You could save the in-memory generated assemblies to disk first if you need to use them.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325