2012-12-13 165 views
0

的Windows 7 SP1 x64的.NET 框架3.5 SP1當刪除目錄

我已經寫了簡單的代碼,但它是通過時間的奇怪的錯誤,除了在每第二次發生。 ...... I.e .:對於偶數的起點:2,4,6,8,e.t.c.都能正常工作,但我對奇數起始點有例外:1,3,5,7,9,e.t.c.

// localMenuDirName is 'GPSM\AdminCAD'. 
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.Programs), localMenuDirName)); 
if (menuDir.Exists) { 
    FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories); 
    foreach (FileInfo file in files) { 
     file.IsReadOnly = false; 
    } 
    sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName)); 

    Directory.Delete(menuDir.FullName, true); // Get Exception here 

    // menuDir.Delete(true); // here I get same exception. 

輸出文本:

我們開始刪除 'C:\用戶\ andrey.bushman \應用程序數據\漫遊\微軟\的Windows \開始菜單 \程序\ GPSM \ AdminCAD' 目錄

例外:該目錄不是空的。

但目錄是空的(所有文件已被刪除)。我打開資源管理器並查看它。

下一頁代碼工作總是罰款:

// localMenuDirName is 'GPSM\AdminCAD'. 
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.Programs), localMenuDirName)); 
if (menuDir.Exists) { 
    FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories); 
    foreach (FileInfo file in files) { 
     file.IsReadOnly = false; 
    } 
    sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName)); 

    try { 
     Directory.Delete(menuDir.FullName, true); 
    } 
    catch { 
     // Try again... Now it works without exception! 
     Directory.Delete(menuDir.FullName, true); 
    } 
    sb.AppendLine("Operation was executed successfully."); 

它爲什麼會發生?

+0

您是否在您嘗試刪除的目錄中的當前目錄下打開了命令提示符? – leppie

+0

也許你有在Windows資源管理器中打開的目錄?然後根據文檔不能刪除它:'在某些情況下,如果您在File Explorer中打開了指定的目錄,則Delete方法可能無法將其刪除。 -us/library/62t64db3.aspx – dognose

+0

@leppie不,我從其他目錄運行我的exe文件,工作目錄也是其他目錄。 –

回答

1

有不同可能的選項,其中Directory.Delete可能失敗,IOException。 根據MSDN

存在具有相同名稱和路徑的文件。

- 或 - 通過路徑指定的目錄是隻讀的,或遞歸爲假,並且路徑不是一個空目錄。

- 或 - 該目錄是應用程序的當前工作目錄。

- 或 - 該目錄包含一個只讀文件。

- 或 - 該目錄被另一個過程。目錄或其中一個文件有一個打開的句柄,操作系統是Windows XP或更早的版本。這個打開的句柄可能來自枚舉目錄和文件。有關更多信息,請參見如何:枚舉目錄和文件。

換句話說:檢查打開的處理程序到那個目錄,檢查隱藏文件。

+0

不,目錄不包含隱藏文件(我創建了這個目錄,我檢查它)。但爲什麼我的第二個代碼工作正常? –

+1

@Bush:對主題沒有*清晰*的想法。只有一名嫌犯。嘗試使用**第一個**代碼,在Directory.Delete之前注入延遲。讓我們說Thread.Sleep(200)。看看它是否像第二種情況那樣工作。 – Tigran

+0

謝謝。它解決了我的問題。現在工作,也是第一個變體(暫停)。但對我而言這很有趣:爲什麼? –