Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if an XDocument File Exists

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!

like image 596
Ian Dallas Avatar asked Dec 10 '22 17:12

Ian Dallas


1 Answers

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
}
like image 167
Aaronaught Avatar answered Dec 20 '22 20:12

Aaronaught