2011-11-09 32 views
1

我正在檢查一個文件是否存在,如果是這樣,我把它放在一個列表中,否則我從列表中刪除。我的代碼是這樣的:File.exists顯示文件,即使它不存在

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

我試過很多方法,但即使文件不存在,列表中也包含它。我可能犯了一個愚蠢的錯誤。

我該怎麼做?

+0

是什麼'System.IO.Path.GetFullPath(namewithext)'的返回值?這個文件在哪裏(網絡共享...)? – Yahia

回答

3

有幾個錯誤代碼:

  • 您設置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); 
    } 
} 
+0

我認爲在循環中使用RemoveAt(i)仍然是一種不好的做法(即使下去)。我會使用一個新的空列表並添加它的有效名稱......(但仍然投票( - :) –

+0

@RoeeGavirel:是的,這是一種方法。使用'List .RemoveAll'是另一個。不想更改原來的代碼:) – Guffa

+0

太棒了!完美的作品,謝謝! :) – user877852

0

您正在通過索引從集合中移除一個項目,然後這個項目將更改集合中剩餘項目的位置。它最終會跳過它應該刪除的條目。

1

有兩個問題與你的代碼,我可以發現:

  1. 獲取引用不存在應該拋出一個異常文件一個FileInfo實例的長度屬性,而不是返回0。

  2. 在第二個for循環中,您可以遍歷您的savedxml列表,但您永遠不會更改「namewithext」變量,這會導致您每次都嘗試刪除相同的條目。

編輯 此外,鄧肯是正確的,當然,如果裏面的代碼中的「if(大小== 0)」分支將永遠運行,你會跳過你的列表中的條目。

0

_savedxml的文件名無誤,所以在_savedxml.Remove(namewithext);namewithext刪除extesnion。

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++; 
} 
相關問題