使用Directory.GetFiles(...)时拒绝访问该路径

Ami*_*aei 14 c#

我正在运行下面的代码并在下面获得例外.我是否被迫将此函数放入try catch中,还是以其他方式递归获取所有目录?我可以编写自己的递归函数来获取文件和目录.但我想知道是否有更好的方法.

// get all files in folder and sub-folders
var d = Directory.GetFiles(@"C:\", "*", SearchOption.AllDirectories);

// get all sub-directories
var dirs = Directory.GetDirectories(@"C:\", "*", SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)

"拒绝访问路径'C:\ Documents and Settings \'."

Mar*_*ell 34

如果你想在失败后继续下一个文件夹,那么是的; 你必须自己做.我建议使用Stack<T>(深度优先)或Queue<T>(bredth优先)而不是递归,以及迭代器块(yield return); 那么你可以避免堆栈溢出和内存使用问题.

例:

    public static IEnumerable<string> GetFiles(string root, string searchPattern)
    {
        Stack<string> pending = new Stack<string>();
        pending.Push(root);
        while (pending.Count != 0)
        {
            var path = pending.Pop();
            string[] next = null;
            try
            {
                next = Directory.GetFiles(path, searchPattern);                    
            }
            catch { }
            if(next != null && next.Length != 0)
                foreach (var file in next) yield return file;
            try
            {
                next = Directory.GetDirectories(path);
                foreach (var subdir in next) pending.Push(subdir);
            }
            catch { }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • @Amir - 迭代器块应该仍然调试好; 但请注意,这是延迟执行; 直到你打电话给'foreach`开始迭代它才会发生.并且它只会在每次循环迭代中执行一次`yield return`(在`foreach`中). (2认同)

Yoc*_*mer 9

您可以设置程序,以便只能以管理员身份运行.

Visual Studio中:

Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
Run Code Online (Sandbox Code Playgroud)

单击它后,将在项目的属性文件夹下创建一个名为app.manifest的文件,一旦创建该文件,您可以取消选中该Enable ClickOnce Security Settings选项

打开该文件并更改此行:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)

至:

 <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)

这将使程序需要管理员权限,并且它将保证您有权访问该文件夹.