XmlSerializer throws FileNotFoundException

Posted by

A very typical scenario when using the XmlSerializer is that at runtime it throws a FileNotFoundException. However, the exception is caught within the XmlSerializer class and program flow continues without any problems.

It is still inconvenient because the exceptions can interfere with your debugging.

Imagine the following code fragment:

Person p = new Person() { Name = "Manu", Age = 33 };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (TextWriter textWriter = new StreamWriter(@"C:\test.xml"))
{     
      serializer.Serialize(textWriter, p);
}

leading to the following exception during debugging:

Iimage

The debugger will only break on the exception if it is set to break on handled exceptions.

There are several solutions to this problem such as creating the serialization assemblies at compile-time etc. The by far easiest solution I came across is to change the instantiation of the XmlSerializer. By replacing:

XmlSerializer serializer = new XmlSerializer(typeof(Person));
with:
XmlSerializer deserializer = 
XmlSerializer.FromTypes(new[] { typeof(Person) })[0]; 

 

 

The exception will not be thrown anymore… *BOOM*

Nice trick! Happy debugging!