Ian*_*las 4 c# linq linq-to-xml
我正在使用LINQ,我想知道创建XDocument的最佳方法是什么,然后检查以确保XDocument实际存在,就像File.Exists一样?
String fileLoc = "path/to/file";
XDocument doc = new XDocument(fileLoc);
//Now I want to check to see if this file exists
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
谢谢!
Aar*_*ght 13
XML文件仍然是一个文件; 只是用File.Exists.
但需要注意的是:File.Exists在加载文档之前,不要试图立即检查.当您尝试打开文件时,无法保证文件仍然存在.编写这段代码:
if (File.Exists(fileName))
{
XDocument doc = XDocument.Load(fileName);
// etc.
}
Run Code Online (Sandbox Code Playgroud)
......是一种竞争条件,总是错的.相反,只需尝试加载文档并捕获异常.
try
{
XDocument doc = XDocument.Load(fileName);
// Process the file
}
catch (FileNotFoundException)
{
// File does not exist - handle the error
}
Run Code Online (Sandbox Code Playgroud)