2012-01-16 36 views
1

如何旁路/忽略「的路徑訪問被拒絕」/UnauthorizedAccess例外如何忽略「訪問路徑被拒絕」/未經授權訪問C#中的異常?

繼續收集在這個方法中的文件名;

public static string[] GetFilesAndFoldersCMethod(string path) 
{ 
    string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray(); 
    return filenames; 
} 

//調用......

foreach (var s in GetFilesAndFoldersCMethod(@"C:/")) 
{ 
    Console.WriteLine(s); 
} 

我的應用程序停止對GetFilesAndFoldersCMethod的firstline和異常說; 「訪問路徑'C:\ @ Logs \'被拒絕。」請幫我...

謝謝,要做到這一點

+0

不看我,就像你可以請求這個方法在遇到錯誤時繼續枚舉。我想你必須推出自己的統計員或找到更靈活的其他班級。 – 2012-01-16 09:21:44

回答

7

最好的辦法是增加一個Try/Catch block來處理異常...

try 
{ 
    string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray(); 
    return filenames; 
} 
catch (Exception ex) 
{ 
    //Do something when you dont have access 
    return null;//if you return null remember to handle it in calling code 
} 

你也可以專門處理UnauthorizedAccessException如果你是在此函數中執行其他代碼,並且要確保它是導致它失敗的訪問異常(此例外由Directory.GetFiles函數拋出)...

try 
{ 
    //... 
} 
catch(UnauthorizedAccessException ex) 
{ 
    //User cannot access directory 
} 
catch(Exception ex) 
{ 
    //a different exception 
} 

編輯:正如在下面的註釋中指出的那樣,它顯示出您正在使用GetFiles函數調用進行遞歸搜索。如果你想要繞過任何錯誤並繼續,那麼你將需要編寫自己的遞歸函數。 There is a great example here這將做你所需要的。下面是這應該是正是你需要的修改...

List<string> DirSearch(string sDir) 
{ 
    List<string> files = new List<string>(); 

    try 
    { 
     foreach (string f in Directory.GetFiles(sDir)) 
     { 
     files.Add(f); 
     } 

     foreach (string d in Directory.GetDirectories(sDir)) 
     { 
     files.AddRange(DirSearch(d)); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 

    return files; 
} 
+0

當然枚舉也會在那裏停止 – 2012-01-16 09:18:35

+0

@DavidHeffernan:是的,但枚舉是在一個字符串數組上 - 這是給定目錄中的所有文件,並且由於目錄引發了訪問異常,所以無論如何所有文件都將無法訪問。我的假設是,如果用戶搜索多個目錄,那麼他們有循環/遞歸函數圍繞示例for循環。當然,我可能會假設錯誤,將不得不等待一個OP響應,以確保 – musefan 2012-01-16 09:23:20

+0

@DavidHeffernan:我的錯誤,我現在看到,GetFiles調用正在做遞歸工作 – musefan 2012-01-16 09:24:53

0

基於MS網頁和各種上嘗試在這裏在stackoverflow,我有一個似乎工作的解決方案,並避免所有的GetFiles()/ GetDirectories()異常。

CF https://stackoverflow.com/a/10728792/89584

(原來的問題可能會被認爲是本一式二份,反之亦然)。