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

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...");
 }

This question confuses "well-formed" with "valid" XML document.

A valid xml document is by definition a well formed document. Additionally, it must satisfy a DTD or a schema (an xml schema, a relaxng schema, schematron or other constraints) to be valid.

Judging from the wording of the question, most probably it asks:

"How to make sure a file contains a well-formed XML document?".

The answer is that an XML document is well-formed if it can be parsed successfully by a compliant XML parser. As the XDocument.Load() method does exactly this, you only need to catch the exception and then conclude that the text contained in the file is not well formed.


Just load it and catch the exception. Same for File.Exists() - the file system is volatile so just because File.Exists() returns true doesn't mean you'll be able to open it.