文件.Exists显示文件,即使该文件不存在

本文关键字:文件 不存在 Exists 显示文件 | 更新日期: 2023-09-27 18:13:51

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

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);
    }
}

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

我该怎么做?

文件.Exists显示文件,即使该文件不存在

代码中有几个错误:

  • 您在第一个循环中为每个项目设置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);
  }
}

我可以发现你的代码有两个问题:

  1. 获取FileInfo实例的Length属性指向一个不存在的文件,应该抛出异常,而不是返回0。

  2. 在第二个for循环中,您遍历savedxml列表,但您从未更改"namewithext"变量,否则会导致您每次都尝试删除相同的条目。

编辑此外,Duncan是对的,当然,如果"if (size == 0)"分支中的代码要运行,那么您将跳过列表中的一个条目。

您正在通过索引从集合中删除一个项目,这将改变集合中其余项目的位置。然后,它将跳过一个本应删除的条目。

_savedxml的文件名没有扩展名,所以在_savedxml.Remove(namewithext);之前要去掉namewithext的扩展名

foreach (KeyValuePair<string, string> kvp in dict)
{
    _savedxml.Add(kvp.Key.ToString());
}
string namewithext = null;
int i = 0;
while (i < _savedxml.Count)
{
    namewithext = string.Concat(_savedxml[i], ".xml");
    System.IO.FileInfo file_info = new System.IO.FileInfo((string)namewithext);
    if (!file_info.Exists || file_info.Length == 0)
        _savedxml.RemoveAt(i);
    else
        i++;
}