本文介绍了的路径访问使用Directory.GetFiles时被拒绝(...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行下面的code和越来越下面例外。我是被迫把这一功能在尝试捕捉或是否有其他方式来获得所有目录递归?
我可以写我自己的递归函数来获取文件和目录。但我不知道是否有更好的方法。

I'm running the code below and getting exception below. Am I forced to put this function in try catch or is there other way to get all directories recursively?I could write my own recursive function to get files and directory. But I wonder if there is a better way.

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

访问路径C:\\ Documents和Settings \\'。被拒绝

"Access to the path 'C:\Documents and Settings\' is denied."

推荐答案

如果你想继续下一个文件夹后失败,那么推倒;你必须自己做。我会建议堆栈< T> (深度优先)或队列< T> (bredth第一),而不是递归和迭代器块(收益回报率);那么你同时避免堆栈溢出和内存使用情况的问题。

If you want to continue with the next folder after a fail, then yea; you'll have to do it yourself. I would recommend a Stack<T> (depth first) or Queue<T> (bredth first) rather than recursion, and an iterator block (yield return); then you avoid both stack-overflow and memory usage issues.

例如:

    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 { }
        }
    }

这篇关于的路径访问使用Directory.GetFiles时被拒绝(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:15
查看更多