How can I dynamically include assemblies when dynamically compiling code?

933 views Asked by At

I have an application in which I compile C# code and launch the output at runtime. This is all going smooth so far, but now I'm trying to compile WinForms applications, I'm running into trouble with the referenced assemblies.

The entire project folder of the WinForms project is in my application, so I retrieve all the referenced assemblies by reading the .csproj-file as an XML-file. So I have the names of the referenced assemblies as strings, such as:

System
Microsoft.CSharp
System.Drawing
System.Windows.Forms            etc.

Is it possible to load these assemblies at runtime knowing just these names? I know their location paths on my system, but the application should also run correctly on someone else's machine.

Update

The compilation is as follows: the code from the classes is retrieved in string format from the class files, those are all stocked in an array. That array is then passed to the CSharpCodeProvider compiler. The application works as intended with just console-programs, but as soon as there are referenced assemblies (such as in WinForms), I have to compile these assemblies too of course.

So what I'm trying to do is to get all the assemblies from the project to be compiled, and then load them so that there won't be missing assembly-errors when executing.

My current code works like this:

var assemblies = AppDomain.CurrentDomain
                        .GetAssemblies()
                        .Where(a => !a.IsDynamic)
                        .Select(a => a.Location);
        parameters.ReferencedAssemblies.AddRange(assemblies.ToArray()); //parameters is CompilerParameters

This works, but is not good way of working because it just adds all referenced assemblies from my Visual Studio (which of course won't work on every machine).

1

There are 1 answers

2
Sievajet On

You must supply a valid fully qualified assembly name:

var assembly = Assembly.Load( @"System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" );

You can get the assemblyname by giving the assembly path:

AssemblyName.GetAssemblyName(@".\UtilityLibrary.dll")

So you got 2 options. Specify the version or the load the specific assembly by file path