Wednesday, January 16, 2013

Loading an Assembly dynamically at runtime

I recently needed to figure out if an assembly loaded at runtime. In particular, I was using this to determine what version of an assembly was being loaded and where it was loaded from when I was trying to troubleshoot a server deployment. The code below can be used to put together a web page that you can hit on the server you are deploying to. The information here can be very valuable when trying to figure out why something is not working properly.

string nameOfDLL = "System.Xml.Linq"; // just an example
bool partialNameGiven = true;

// flag if the load failed or succeeded
bool successfullyLoaded;

try
{
    Assembly asm;
    if (partialNameGiven)
    {
        asm = Assembly.LoadWithPartialName(nameOfDLL);
    }
    else
    {
        AssemblyName asmName = new AssemblyName(nameOfDLL);
        asm = Assembly.Load(asmName);
    }

    if (asm != null)
    {
        // loaded the assembly so get some basic info about it
        string loadedAssemblyName = asm.FullName;
        string location = asm.Location;
        successfullyLoaded = true;
    }
    else
    {
        // couldn't load the assembly
        successfullyLoaded = false;
    }
}
catch (Exception ex)
{
    // do error handling here
    successfullyLoaded = false;
}

No comments: