tags:

views:

137

answers:

1

Hello Everyone,

I am using LINQ and I was wondering what is the best way to create an XDocument and then check to make sure that the XDocument actually exists, much like File.Exists?

String fileLoc = "path/to/file";
XDocument doc = new XDocument(fileLoc);
//Now I want to check to see if this file exists

Is there a way to do this?

Thanks!

+3  A: 

An XML file is still a file; just use File.Exists.

Just a cautionary note, though: Don't bother trying to check File.Exists immediately before loading the document. There is no way to guarantee that the file will still be there when you try to open it. Writing this code:

if (File.Exists(fileName))
{
    XDocument doc = XDocument.Load(fileName);
    // etc.
}

...is a race condition and always wrong. Instead, just try loading the document and catch the exception.

try
{
    XDocument doc = XDocument.Load(fileName);
    // Process the file
}
catch (FileNotFoundException)
{
    // File does not exist - handle the error
}
Aaronaught