Why would Assembly.GetExecutingAssembly() return null?

Nathan picture Nathan · Mar 4, 2010 · Viewed 12.9k times · Source

I am using a xml file as an embedded resource to load an XDocument. We are using the following code to get the appropriate file from the Assembly:

XDocument xd = new XDocument();
Assembly assembly = null;

try
{
    assembly = Assembly.GetExecutingAssembly();
}
catch(Exception ex)
{
    //Write exception to server event log
}

try
{
    if(assembly != null)
    {
        using(StreamReader sr = new 
            StreamReader(assembly.GetManifestResourceStream("assemblyPath")))
        {
            using(XmlTextReader xtr = new XmlTextReader(sr))
            {
                xd = XDocument.Load(xtr);
            }
        }
    }
}
catch(Exception ex)
{
    //Write exception to server event log
}

So when the code is deployed, we occasionally will go to the page and nothing will be loaded from the embedded document. When we check the event log, there is no error. If the user just refreshes the page, it'll load fine. This has lead me to think that, for some reason, assembly = Assembly.GetExecutingAssembly(); is ocassionally returning null, and the way the code is written this isn't an error. So, my question is why would Assembly.GetExecutingAssembly(); be returning null? I found a couple articles talking about there being errors sometimes with unmanaged code, but this application is written in C# and deployed via setup project.

The code was originally written without error avoidance code. It was added to keep the users from getting error screens. The exceptions are written to the event log of the server.

Answer

Aaronaught picture Aaronaught · Mar 4, 2010

This is a perfect example of why it's an almost universally bad idea to eat exceptions, especially the top-level System.Exception. The problem could be anywhere; more likely than not, the real problem is in your logging code.

Take out those empty catch blocks (or rethrow inside them with throw;) and see where the exception is really occurring. And once you find the real problem and rewrite your code, rewrite it to catch only exceptions that you actually know how to handle.

GetExecutingAssembly will not return null, period.