C# 获取将返回列表的文件夹和子文件夹中所有文件的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14305581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:23:01  来源:igfitidea点击:

Method to get all files within folder and subfolders that will return a list

c#filemethodsrecursiondirectory

提问by Wilson

I have a method that will iterate through a folder and all of its subfolders and get a list of the file paths. However, I could only figure out how to create it and add the files to a public List, but not how to return the list. Here's the method:

我有一种方法可以遍历文件夹及其所有子文件夹并获取文件路径列表。但是,我只能弄清楚如何创建它并将文件添加到公共列表中,而不能弄清楚如何返回列表。这是方法:

public List<String> files = new List<String>();

private void DirSearch(string sDir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                DirSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

So, i just call DirSearch()at some point in my code and it 'fills' the list with the paths, but I want to be able to use it multiple times to create different lists with different directories, etc.

所以,我只是DirSearch()在我的代码中的某个时候调用它并用路径“填充”列表,但我希望能够多次使用它来创建具有不同目录等的不同列表。

采纳答案by Darin Dimitrov

private List<String> DirSearch(string sDir)
{
    List<String> files = new List<String>();
    try
    {
        foreach (string f in Directory.GetFiles(sDir))
        {
            files.Add(f);
        }
        foreach (string d in Directory.GetDirectories(sDir))
        {
            files.AddRange(DirSearch(d));
        }
    }
    catch (System.Exception excpt)
    {
        MessageBox.Show(excpt.Message);
    }

    return files;
}

and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer.

如果您不想将整个列表加载到内存中并避免阻塞,您可以查看following answer.

回答by Mir

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearchto:

我不确定为什么要将字符串添加到files,它被声明为字段而不是临时变量。您可以将签名更改DirSearch为:

private List<string> DirSearch(string sDir)

And, after the catchblock, add:

并且,在catch块之后,添加:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

或者,您可以在方法中创建一个临时变量并返回它,这在我看来是您可能想要的方法。否则,每次调用该方法时,新找到的字符串将添加到与以前相同的列表中,并且您将有重复项。

回答by Tilak

You can use Directory.GetFilesto replace your method.

您可以使用Directory.GetFiles来替换您的方法。

 Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)

回答by Tommaso Belluzzo

Simply use this:

只需使用这个:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
}

And if you want every file, even extensionless ones:

如果你想要每个文件,甚至是无扩展名的文件:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
}

回答by sam

you can use something like this :

你可以使用这样的东西:

string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

instead of using "." you can type the name of the file or just the type like "*.txt" also SearchOption.AllDirectories is to search in all subfolders you can change that if you only want one level more about how to use it on here

而不是使用“ .”,您可以键入文件的名称或仅键入“ * .txt”之类的类型也 SearchOption.AllDirectories 是在所有子文件夹中搜索您可以更改它,如果您只想要一个关于如何使用它的级别在这里

回答by Ris

Try this
class Program { static void Main(string[] args) {

试试这个
类 Program { static void Main(string[] args) {

        getfiles get = new getfiles();
        List<string> files =  get.GetAllFiles(@"D:\Rishi");

        foreach(string f in files)
        {
            Console.WriteLine(f);
        }


        Console.Read();
    }


}

class getfiles
{
    public List<string> GetAllFiles(string sDirt)
    {
        List<string> files = new List<string>();

        try
        {
            foreach (string file in Directory.GetFiles(sDirt))
            {
                files.Add(file);
            }
            foreach (string fl in Directory.GetDirectories(sDirt))
            {
                files.AddRange(GetAllFiles(fl));
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);
        }



        return files;
    }
}

回答by Veera Induvasi

String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);

回答by Aubrey Love

This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document. Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc. I tried commenting as much as possible throughout the code so you could understand what each part is doing. This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can't do something with it. Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders. This example code will get all the files and create a list in a text document and place that text document in Folder1. Caution: you shouldn't save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.

这适用于试图获取文件夹及其子文件夹中所有文件的列表并将其保存在文本文档中的任何人。下面是完整的代码,包括“使用”语句、“命名空间”、“类”、“方法”等。我尝试在整个代码中尽可能多地注释,以便您了解每个部分在做什么。这将创建一个文本文档,其中包含任何给定根文件夹的所有文件夹和子文件夹中的所有文件的列表。毕竟,如果你不能用它做点什么,列表(比如在 Console.WriteLine 中)有什么用。在这里,我在 C 驱动器上创建了一个名为“Folder1”的文件夹,并在该文件夹中创建了一个名为“Folder2”的文件夹。接下来,我用一堆文件、文件夹以及这些文件夹中的文件和文件夹填充了 folder2。此示例代码将获取所有文件并在文本文档中创建一个列表并将该文本文档放置在 Folder1 中。注意:您不应该将文本文档保存到 Folder2(您正在阅读的文件夹),这将是不好的做法。始终将其保存到另一个文件夹。
我希望这可以帮助某人下线。

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Create a header for your text file
            string[] HeaderA = { "****** List of Files ******" };
            System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);

            // Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
            // named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
            string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
            {
                //Now that we have a list of files, write them to a text file.
                WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
            }

            // Now, append the header and list to the text file.
            using (System.IO.StreamWriter file =
                new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
            {
                // First - call the header 
                foreach (string line in HeaderA)
                {
                    file.WriteLine(line);
                }

                file.WriteLine(); // This line just puts a blank space between the header and list of files. 


                // Now, call teh list of files.
                foreach (string name in arrayA)
                {
                    file.WriteLine(name);
                }

            }
          }


        // These are just the "throw new exception" calls that are needed when converting the array's to strings. 

        // This one is for the Header.
        private static void WriteAllLines(string v, string file)
        {
            //throw new NotImplementedException();
        }

        // And this one is for the list of files. 
        private static void WriteAllLines(string v, string[] arrayA)
        {
            //throw new NotImplementedException();
        }



    }
}