views:

52

answers:

1

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        string xml = @"<ArrayOfUserSetting>
                            <UserSetting>
                                <Value>Proposals</Value>
                                <Name>LastGroup</Name>
                            </UserSetting>
                            <UserSetting>
                                <Value>Visible</Value>
                                <Name>WidgetsVisibility</Name>
                            </UserSetting>
                        </ArrayOfUserSetting>";

        List<UserSetting> settings = 
                 GetObjFromXmlDocument<List<UserSetting>>(xml);
    }

    public static T GetObjFromXmlDocument<T>(string xml)
    {
        T customType;

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xml);
        using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument))
        {
            customType = (T)serializer.Deserialize(xmlNodeReader);
        }

        return customType;
    }
}

[Serializable]
public class UserSetting
{
    public string Value { get; set; }
    public string Name { get; set; }
}

The code works fine and the call to GetObjFromXmlDocument yields a List collection. However, I always get a first chance exception of type System.IO.FileNotFoundException in mscorlib.dll, when XmlSerializer serializer = new XmlSerializer(typeof(T)); is executed.

So I went into Debug/Exception and turned on Managed Debugging Assistants. I got the following on that line:

The assembly with display name 'mscorlib.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified. File name: 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Can someone explain why this is happening? Is there something I could do to the UserSetting class to make the problem disappear? The application is quite performance sensitive and I'd rather not have the exception.

+2  A: 

Microsoft says:

XmlSerializer attempts to load pre-generated serializers to avoid compilation of the serialization code on the fly. There is no easy way to check for "will assembly be found by the Assembly.Load() call", it would be duplicating Fusion path search and loader logic in XmlSerializer.

http://connect.microsoft.com/VisualStudio/feedback/details/93647/xml-serializer-throws-file-not-found-exceptions

It looks like a FileNotFound exception is thrown and handled in the XmlSerializer when the "pre-generated serializer" cannot be found, which will then cause the serialization code to be generated.

fletcher