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!
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With