DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 5.7 Debugging Problems whenLoading an Assembly

Problem

You want to use a reflection-based technique, such as the static Assembly.LoadFrom method, to load an assembly. If this method fails, you want to collect as much useful information you can as to why this assembly failed to load.

Solution

Either call the ToString method on the exception object thrown or use the FusionLog property on BadImageFormatException, FileLoadException, or FileNotFoundException. When an exception occurs while using a file, the exception contains extra information that is taken from the fusion log. To see this in action, run the following code:

public static void LoadMissingDLL( )
{
    // Load the DLL
    try
    {
        Assembly reflectedAssembly = Assembly.LoadFrom("BadFileName.dll");
    }
    catch (FileNotFoundException fnf)
    {
        // This displays the fusion log information only
        Console.WriteLine(fnf.FusionLog);
    }
    catch (Exception e)    // Note that you would use one catch block or the other,
    {                      //    not both
        // This displays the exception information along
        // with any fusion log information
        Console.WriteLine(e.ToString( ));
    }
}

Discussion

Use this technique to debug problems when loading an assembly from a file. When using the ToString method of the Exception object, notice the bottom part of the error message that starts with "Fusion log follows." This is the section that can provide some clue as to why the reflection APIs could not find your assembly. If you want just the fusion information, you can use the FusionLog property of one of the aforementioned exception objects.

See Also

See the "BadImageFormatException Class," "FileLoadException Class," and "FileNotFoundException Class" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section