【问题标题】:Determining if an XDocument File Exists确定 XDocument 文件是否存在
【发布时间】:2010-03-09 08:18:33
【问题描述】:

我正在使用 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

有没有办法做到这一点?

谢谢!

【问题讨论】:

  • 为什么不先检查 File.Exists?
  • 嗯,我想到了,但据我所知,没有办法从文件创建 XDocument...如果有,请告诉我 :)

标签: c# linq linq-to-xml


【解决方案1】:

XML 文件仍然是文件;只需使用File.Exists

不过,请注意:不要在加载文档之前立即尝试检查File.Exists。当您尝试打开文件时,无法保证该文件仍然存在。编写此代码:

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

...是一种竞争条件,总是错误的。相反,只需尝试加载文档并捕获异常。

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

【讨论】:

  • 不明白为什么这是一个竞争条件。请您详细说明一下?
猜你喜欢
  • 2011-02-12
  • 2014-10-15
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多