How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?

adeena picture adeena · Dec 17, 2008 · Viewed 42.2k times · Source

I'm loading an XML document in my C# application with the following:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);

but before that, I do test to make sure the file exists with:

File.Exists(myfile);

But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.

The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "

Thanks!

-Adeena

Answer

Jennifer picture Jennifer · Dec 17, 2008

It's probably just worth catching the specific exception if you want to show a message to the user:

 try
 {
   XDocument xd1 = new XDocument();
   xd1 = XDocument.Load(myfile);
 }
 catch (XmlException exception)
 {
     ShowMessage("Your XML was probably bad...");
 }