问题
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.
回答1:
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.
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.
回答2:
For the select few Visual Studio projects I have where this is an annoyance, I prefer to disable break on exception for just the BindingFailure and the System.IO.FileNotFoundException.
In Visual Studio: Ctl-D, Ctl-E for the Exceptions dialog:
1) Uncheck BindingFailure under Managed Debugging Assistants
2) Uncheck System.IO.FileNotFoundException under Common Language Runtime Exceptions.
Ahhh that’s better :-)
来源:https://stackoverflow.com/questions/3517470/why-am-i-getting-a-serialization-error