Determining the existence of an XDocument file

I am using LINQ and I was wondering what is the best way to create an XDocument and then check if an XDocument really exists, 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 any way to do this?

Thanks!

+4
source share
1 answer

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

Just a cautionary note: Do not try to check File.Exists just before loading the document. There is no guarantee that the file will still be present when you try to open it. Writing this code:

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

... is a condition of race and always erroneous. 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 } 
+11
source

Source: https://habr.com/ru/post/1303518/


All Articles