XmlSerializer throws FileNotFoundException

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!

Category:Business
Tag:,
PREVIOUS POST
Enable BizTalk Tracking–The message was not found in the Message Box or the Tracking database
NEXT POST
Windows 8 First Contact and first Problems: Installing Windows 8 To Go
15 49.0138 8.38624 1 0 4000 1 https://manuelmeyer.net 300 0