c# - File.exists 显示文件,即使它不存在

标签 c# visual-studio-2008 file-io

我正在检查文件是否存在,如果存在,我将其放入列表中,否则我将其从列表中删除。我的代码是这样的:

foreach (KeyValuePair<string, string> kvp in dict)
{
    _savedxml.Add(kvp.Key.ToString());
}

string namewithext=null;
for (int i = 0; i < _savedxml.Count; i++)
{
    namewithext = string.Concat(_savedxml[i], ".xml");
    System.IO.FileInfo file_info = new System.IO.FileInfo((string)namewithext);
    long size = file_info.Length;
    if (size == 0)
    {
        _savedxml.RemoveAt(i);
    }
}

for (int i = 0; i < _savedxml.Count; i++)
{
    if (System.IO.File.Exists(System.IO.Path.GetFullPath(namewithext)))
    {
    }
    else
    {
        _savedxml.Remove(namewithext);
    }
}

我尝试了很多方法,但即使文件不存在,列表中也包含它。我可能犯了一个愚蠢的错误。

我该怎么做?

最佳答案

代码中有几个错误:

  • 您在第一个循环中为每个项目设置了 namewithext 变量,然后在第二个循环中使用它,因此您将反复检查最后一个文件是否存在。

  • 当您删除一个项目时,下一个项目将取代它在列表中的位置,因此您将跳过对下一个项目的检查。

  • 您在检查文件是否存在之前检查文件的长度,因此当您尝试获取不存在的文件的长度时,您将得到一个 FileNotFoundException

更正(和一些清理):

foreach (KeyValuePair<string, string> kvp in dict) {
  _savedxml.Add(kvp.Key);
}

for (int i = _savedxml.Count - 1; i >= 0 ; i--) {
  string namewithext = _savedxml[i] + ".xml";
  if (!System.IO.File.Exists(System.IO.Path.GetFullPath(namewithext))) {
    _savedxml.RemoveAt(i);
  }
}

for (int i = _savedxml.Count - 1; i >= 0 ; i--) {
  string namewithext = _savedxml[i] + ".xml";
  System.IO.FileInfo file_info = new System.IO.FileInfo(namewithext);
  if (file_info.Length == 0) {
    _savedxml.RemoveAt(i);
  }
}

关于c# - File.exists 显示文件,即使它不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8063508/

相关文章:

c# - 在 C# 中使用 Y 组合器

c# - nVarchar 和 SqlParameter

C#线程使用调用,卡住表单

c# - 解决方案范围 app.config/web.config?

python - 在 Python 中读取和写入文件

c - C 中的分割文件错误在 readfile 中获取缓冲区

visual-studio-2008 - 链接错误 : unresolved external symbol ___cudaRegisterLinkedBinary referenced in function ____cudaRegisterAll

c# - 什么相当于 Visual Studio 2010 中的 Visual Studio 2008 对象测试台?

visual-studio-2008 - TFS 生成错误 TF224003、TF215085、TF215076

java - 将项目添加到 JList 删除所有其他项目