简体   繁体   English

如何使用“Directory.getFiles”获取具有特定扩展名的磁盘上的所有文件并将其保存在列表中

[英]How can i get all files on disk with a specific extension using 'Directory.getFiles' and save them in a list

I'm doing a console project whose goal is to search the entire disk for all files with the extension '.config' 我正在做一个控制台项目,其目标是在整个磁盘上搜索扩展名为“.config”的所有文件

I've tried something like: 我尝试过类似的东西:

foreach (string file in Directory.GetFiles("C:\\", "*.config", SearchOption.AllDirectories))
  {
   Console.WriteLine(file);
   Console.ReadLine();
}

but gave me an error "denied access to path (...)". 但给了我一个错误“拒绝访问路径(...)”。

On the internet I found this code: 在互联网上,我发现这个代码:

Stack<string> pending = new Stack<string>();
        pending.Push("C:\\");

        while (pending.Count != 0)
        {
            var path = pending.Pop();
            string[] next = null;

            try
            {
                next = Directory.GetFiles(path, "*.config");
            }
            catch { }

            if (next != null && next.Length != 0)
                foreach (var file in next)
                {
                    Console.WriteLine(file);
                    Console.ReadLine();
                }
            try
            {
                next = Directory.GetDirectories(path);
                foreach (var subdir in next) pending.Push(subdir);
            }
            catch { }
        }

but it just shows the path clicking always in 'enter' and I want to save those files/path in a list. 但它只显示总是在'enter'中单击的路径,我想在列表中保存这些文件/路径。

Someone can help? 有人可以帮忙吗?

Replace the lines 替换线

Console.WriteLine(file);
Console.ReadLine();

with a method to store them in a list. 用一种方法将它们存储在列表中。
For example 例如

foundFiles.Add(file);

Then when the method is done, you can read all found file paths from this list. 然后,当方法完成后,您可以从此列表中读取所有找到的文件路径。

Notes: 笔记:
This will not yield all files on the system that match the filter. 这不会产生系统上与过滤器匹配的所有文件。
Only files where your application has access to their respective directory are found this way. 只有这样才能找到应用程序可以访问其各自目录的文件。
For example the Windows directory and user directories of other users are usually protected. 例如,其他用户的Windows目录和用户目录通常受到保护。 (assuming you run on Windows) (假设您在Windows上运行)

Keep in mind, that some files might be protected independently of their directory. 请记住,某些文件可能会受到独立于其目录的保护。
So when trying to read them, also consider the fact, that the read might fail. 因此,在尝试阅读它们时,还要考虑读取可能失败的事实。
Just encompass the read with a try catch. 只是用try catch包含读取。

There are two things you can do to improve that code: 您可以采取两项措施来改进该代码:

  1. Use Directory.EnumerateFiles() and Directory.EnumerateDirectories() to avoid making a copy of the names of all the files in each directory. 使用Directory.EnumerateFiles()Directory.EnumerateDirectories()可以避免复制每个目录中的所有文件的名称。
  2. Make the return type of the method IEnumerable<string> to make it easier to consume. 使IEnumerable<string>方法的返回类型更容易使用。

We also need to be very careful about exceptions caused by attempting to access protected files and directories. 我们还需要非常小心尝试访问受保护文件和目录所导致的异常。 The code below is also complicated by the fact that you're not allowed to yield return from inside a try/catch block, so we have to rearrange the code somewhat. 下面的代码也很复杂,因为你不允许从try/catch块中yield return ,所以我们必须稍微重新排列代码。

(Also note that we have to dispose the enumerator returned from .GetEnumerator() ; normally this is done automatically when you use foreach , but in this case we can't - because of having to avoid doing yield return in a try/catch - so we have to use using to dispose it.) (另请注意,我们必须处理从.GetEnumerator()返回的枚举器;通常这是在使用foreach时自动完成的,但在这种情况下我们不能 - 因为必须避免在try/catch执行yield return -所以我们必须使用using处置它。)

Here's a modification of your original code to do this: 以下是对原始代码的修改:

public static IEnumerable<string> GetFiles(string root, string spec)
{
    var pending = new Stack<string>(new []{root});

    while (pending.Count > 0)
    {
        var path = pending.Pop();
        IEnumerator<string> fileIterator = null;

        try
        {
            fileIterator = Directory.EnumerateFiles(path, spec).GetEnumerator();
        }

        catch {}

        if (fileIterator != null)
        {
            using (fileIterator)
            {
                while (true)
                {
                    try
                    {
                        if (!fileIterator.MoveNext()) // Throws if file is not accessible.
                            break;
                    }

                    catch { break; }

                    yield return fileIterator.Current;
                }
            }
        }

        IEnumerator<string> dirIterator = null;

        try
        {
            dirIterator = Directory.EnumerateDirectories(path).GetEnumerator();
        }

        catch {}

        if (dirIterator != null)
        {
            using (dirIterator)
            {
                while (true)
                {
                    try
                    {
                        if (!dirIterator.MoveNext()) // Throws if directory is not accessible.
                            break;
                    }

                    catch { break; }

                    pending.Push(dirIterator.Current);
                }
            }
        }
    }
}

As an example, here's how you could use a console app to list all the accessible ".txt" files on the "C:\\" drive: 例如,以下是如何使用控制台应用程序列出“C:\\”驱动器上所有可访问的“.txt”文件:

static void Main()
{
    foreach (var file in GetFiles("C:\\", "*.txt"))
    {
        Console.WriteLine(file);
    }
}

关于错误“拒绝访问路径(...)”,有时您必须以管理员身份运行Visual Studio才能访问C:\\驱动器中的某些文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Directory.GetFiles()选择除特定扩展名之外的所有文件 - Using Directory.GetFiles() to select all the files but a certain extension 使用Directory.GetFiles获取名称中没有特定单词的文件 - Get files with no specific word in the name using Directory.GetFiles 我如何使用directory.getfiles仅过滤.sql文件 - how can i filter only .sql files using directory.getfiles Directory.GetFiles没有获取特定文件 - Directory.GetFiles not getting specific files Directory.GetFiles使用filePattern获取多个文件 - Directory.GetFiles get multiple files using filePattern C#:使用Directory.GetFiles获取固定长度的文件 - C#: Using Directory.GetFiles to get files with fixed length directory.GetFiles,我如何让它在找到它们时吐出物品? - directory.GetFiles, how do i get it to spit out items as it finds them? 如何在C#中使用Directory.GetFiles()添加多个文件? - How to add multiple files using Directory.GetFiles() in C#? C#如何在不使用Directory.GetFiles()方法的情况下遍历文件列表 - C# How to iterate through a list of files without using Directory.GetFiles() method 使用Directory.GetFiles查询文件夹中文件列表时如何知道排序类型? - How to know the sort type when querying the list of files in a folder using Directory.GetFiles?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM