I use the following code to serialize xml file.
I wonder whether should I use the CanDeserialize function in this case.
I noticed that CanDeserialize throws XmlException if the file is empty.
Deserialize throws InvalidOperationException in that case.
My question is should I remove that extra check and if Deserialize does some sort of check anyway?
EDIT: After reading some comments and answers, I wonder when to use CanDeserialize ?
public static T RestoreFromXml(string filename)
{
Object res = null;
using (var stream = new FileStream(filename, FileMode.Open))
{
XmlReader reader = new XmlTextReader(stream);
try
{
if (xs.CanDeserialize(reader))
{
res = xs.Deserialize(reader);
}
}
catch (XmlException ex)
{
throw ex;
}
}
return (T)res;
}
You can do some checkings before trying to deserialize – check if the file name is not null or empty, check if the file exists, etc. Here’s some code to deserialize a file:
}
You can use it like this:
This code was taken from an article that I wrote, you can find it here:
XML serialization using Generics