2014-01-16 43 views
0

因此,我們有一個應用程序,用戶不斷丟失其工具欄,解決問題的唯一方法是刪除該用戶的應用程序數據中的文件夾。因此,我們寫了一個簡單的小程序,在這裏刪除這個文件夾就是我們在try catchC#Directory.Delete投擲非法字符錯誤

System.ArgumentException: Illegal characters in path. 
    at System.IO.Path.CheckInvalidPathChars(String path) 
    at System.IO.Path.InternalCombine(String path1, String path2) 
    at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive) 
    at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive) 
    at System.IO.Directory.Delete(String path, Boolean recursive) 
    at DeleteFolder.frnDeleteFolder.btnDelete_Click(Object sender, EventArgs e) in C:\Users\rmcintosh.K12.000\documents\visual studio 2010\Projects\DeleteFolder\DeleteFolder\frnDeleteFolder.cs:line 82 

這裏得到的錯誤是我們使用刪除

string path = @"C:\Users\98532153\AppData\Roaming\DraftSight"; 
    try 
    { 
     if (Directory.Exists(path)) { 
      Directory.Delete(path, true); 
     } 
     else 
     { 
      MessageBox.Show("Directory Does Not Exists"); 
     } 

    } 
    catch (Exception ex) 
    { 
     richTextBox1.Text = ex.ToString(); 
    } 

我想指出的代碼這個工作發現只要主目錄是空的,但只要我添加任何文件子目錄,它會引發此錯誤。

+0

檢查以確保路徑中沒有多餘的引號,並且路徑不以斜線結尾。 – Marko

+0

刪除了路徑末尾的斜槓。 –

+1

試試這個'string path = @「C:\ Users \ 98532153 \ AppData \ Roaming \ DraftSight」;' –

回答

3

C#字符串中的反斜槓是一個轉義字符;你需要string path = @"C:\Whatever\Wherever"; - 注意'@' - 或者你需要string path = "C:\\Whatever\\Wherever"; - 注意雙反斜線。

您可以閱讀更多關於string literals on MSDN

0

看起來像內部的一些子目錄可能在名稱中有一些無效字符。不知何故.NET不處理它。唯一的方法是編寫自己的例程,遞歸地檢查路徑並刪除它們。

0

如果您查看VS中的Intellisense,它會告訴您該目錄必須爲空。

調用Directory.GetFiles並清除它們,然後刪除該目錄。

如果你需要我可以幫你用遞歸方法來做到這一點。

+0

'Directory.Delete(path,true)'遞歸刪除所有文件和目錄。 http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx –