Skip to main content
 首页 » 编程设计

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

2024年02月23日15shihaiming

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

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