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?

1
  • 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. Commented Sep 2, 2014 at 11:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

14 Comments

I do some pre-process on my assemblies and load them on memory. I have their Assembly object. In this case can I use your code?
Sure. Give it a try and tell me if you experience any problems.
If that wrong? You can't just put there in-memory assemblies as explained in the post.
No, but you can save it first. Set the compilerParams.OutputAssembly to a file path.
Too bad. Also see Hans' comment. I think there is not much to do.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.