yash fale
yash fale

Reputation: 331

how to check xDocument is null or Empty in c#

I want to handle the empty file which does not contain any data after running below code it gives error like root element is missing.

How can I check xDoc is null or empty?

string path = @"E:\Test.xml";
XDocument xDoc = XDocument.Load(path);

Upvotes: 1

Views: 5870

Answers (1)

Ralf Bönning
Ralf Bönning

Reputation: 15415

XDocument.Load expects a valid XML file. Otherwise an exception will be thrown. You can either check, if the file exists or is empty before calling XDocument.Load , e.g. via

if (new System.IO.FileInfo(path).Length > 0)
{
   ...
}

or you can catch the exception.

string path = @"E:\Test.xml";
try
{
    XDocument xDoc = XDocument.Load(path);
} catch(Exception) {
   // some problem
}

If this code is put into a static function the code would be more readable.

 var xDoc = MyXDocument.Load(path);
 if (xDoc != null)
 { .... 
 }

public class MyXDocument {
    public static XDocument Load(string path) {
        try
        {
             XDocument xDoc = XDocument.Load(path);
             return xDoc;
        } catch(Exception) {
            return null;
        }
    }
}

Upvotes: 1

Related Questions