Loading Additional .NET Assemblies

June 1, 2020

There are times you want to add an additional .NET library to your code. It might be an actual Microsoft assembly or from another vendor.

First you import CLR then add the desired assembly. (Note that the DLL must be either in the GAC or the executable folder.) Finally import the type/class namespace(s).

import clr
clr.AddReference("System.Drawing")
from System.Drawing import *

# Initialize a Color struct.
c = Color.FromKnownColor(KnownColor.Red)

If you want to minimize the types brought into the application from the assembly, you can use a more targeted approach and only import the desired type/class namespaces. This is used to avoid namespace pollution that can create naming collisions between classes.

import clr
clr.AddReference("System.Drawing")
from System.Drawing import Color, KnownColor    # Specify desired types!

# Initialize a Color struct.
c = Color.FromKnownColor(KnownColor.Red)

Determine Loaded Assemblies

What if we need to determine which assemblies are already loaded by the runtime? We can determine this by using reflection on assembly itself.

from System import *
assemblies = AppDomain.CurrentDomain.GetAssemblies()

Load Assemblies from Other Folders

This is simple. By using one of the Assembly.AddReference… variants we can load a DLL in (nearly) any folder. Be aware that security policies will restrict where we can access. As always, be sure and import the desired class/type.

import clr
clr.AddReferenceToFileAndPath("C:\\Dev\\CustomLibrary.dll")
from CustomLibrary import WidgetClass