Tuesday, February 25, 2014

Find DLL location in Global Assembly Cache (GAC)

This method will give the location of an assembly from GAC



private string FindDLLInGAC(string dll)
{    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
    {        if (a.ManifestModule.ScopeName.Equals(dll))
             return a.Location;
    }     return null; //Not found
}

//Usage
string asmLocation = FindDLLInGAC("TheDLL.dll");
Assembly asm = Assembly.LoadFile(asmLocation);
var thetype = asm.GetType(theType, true, false);

Monday, February 24, 2014

Load Assembly to dynamically create an instance of a class


This will load an assembly and dynamically create an instance of a class.


...
string asmLocation = Path.Combine(AssemblyDirectory(), "TheDLL.dll");
Assembly asm = Assembly.LoadFile(asmLocation);
var theType = asm.GetType("TheType", true, false);
IRunnable runnable = Activator.CreateInstance(theType) as IRunnable;

runnable.Execute();
...

 
private string AssemblyDirectory()
{    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
           
    return Path.GetDirectoryName(path);
}