枚举文件引发异常 [英] Enumerating Files Throwing Exception

查看:91
本文介绍了枚举文件引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码枚举计算机中的文件,但每次遇到我无权读取的文件或目录时,都会引发异常。引发异常后,有什么方法可以继续搜索?我知道有些人也有类似的问题,但是除了单独检查每个文件/文件夹之外,还有其他方法吗?

I am trying to enumerate through files on my computer using the below code but everytime it hits a file or dir that I don't have permission to read it throws an exception. Is there any way I can continue searching after the exception has been thrown? I know some people have had similar issues but is there any other way of doing this other than checking every file/folder individually?

try
{
    string[] files = Directory.GetFiles(@"C:\", *.*",SearchOption.AllDirectories);
    foreach (string file in files)
    {
       Console.WriteLine(file);
    }
}
catch
{
}

感谢您的帮助,这使我发疯了!

Thanks for any help as this is driving me mad!

推荐答案

我今天遇到了同样的问题。我一起破解了以下代码。如果您想在实际产品中使用它,则可能需要改进错误处理。因为这是一个脚本的,所以我没有

I came across the same problem just today. I hacked together the following code. If you want to use it in a real product you might need to improve the error handling. Since this was for a one-shot script I didn't care much.

static IEnumerable<string> EnumerateFilesRecursive(string root,string pattern="*")
{
    var todo = new Queue<string>();
    todo.Enqueue(root);
    while (todo.Count > 0)
    {
        string dir = todo.Dequeue();
        string[] subdirs = new string[0];
        string[] files = new string[0];
        try
        {
            subdirs = Directory.GetDirectories(dir);
            files = Directory.GetFiles(dir, pattern);
        }
        catch (IOException)
        {
        }
        catch (System.UnauthorizedAccessException)
        {
        }

        foreach (string subdir in subdirs)
        {
            todo.Enqueue(subdir);
        }
        foreach (string filename in files)
        {
            yield return filename;
        }
    }
}

要使用它,您可以:

string[] files = EnumerateFilesRecursive(@"C:\").ToArray();//Note the ToArray()
foreach (string file in files)
{
   Console.WriteLine(file);
}

首先枚举所有文件,将所有文件名存储在内存中,然后才显示他们。或者,您可以:

which first enumerates all files, stores all file names in memory and only then displays them. Alternatively you can:

IEnumerable<string> files = EnumerateFilesRecursive(@"C:\");//Note that there is NO ToArray()
foreach (string file in files)
{
   Console.WriteLine(file);
}

枚举时写入,因此不需要将所有文件名保留在内存中同时。

Which writes while enumerating and thus doesn't need to keep all filenames in memory at the same time.

这篇关于枚举文件引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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