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

问题描述 投票:0回答:9

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

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

所以,我只是在代码中的某个时刻调用

DirSearch()
,它会用路径“填充”列表,但我希望能够多次使用它来创建具有不同目录的不同列表等。

c# file methods recursion directory
9个回答
180
投票

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

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

61
投票
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;
}

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

following answer


26
投票

只需使用这个:

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

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

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

15
投票

你可以使用这样的东西:

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

您可以键入文件名或仅键入“*.txt”等类型,而不是使用“.” 另外 SearchOption.AllDirectories 是在所有子文件夹中搜索,如果您只想要一级,您可以更改它 更多关于如何使用它的信息请参见这里


3
投票

我不确定为什么要将字符串添加到

files
,它被声明为字段而不是临时变量。您可以将
DirSearch
的签名更改为:

private List<string> DirSearch(string sDir)

并且,在

catch
块之后添加:

return files;

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


3
投票

这适用于尝试获取文件夹及其子文件夹中所有文件的列表并将其保存在文本文档中的任何人。 下面是完整的代码,包括“using”语句、“命名空间”、“类”、“方法”等。 我尝试在整个代码中尽可能多地进行注释,以便您可以理解每个部分的作用。 这将创建一个文本文档,其中包含任何给定根文件夹的所有文件夹和子文件夹中的所有文件的列表。毕竟,如果您不能用列表(例如在 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();
        }



    }
}

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

1
投票

LINQ解决方案:

public IEnumerable<FileInfo> DirSearch(string sDir){
            var directoryInfo = new DirectoryInfo(sDir);
            return directoryInfo.GetDirectories()
                .SelectMany(directory => DirSearch(directory.FullName))
                .Union(directoryInfo.GetFiles());
}

这将返回 FileInfos 而不是字符串,因为我认为它们更容易使用。


0
投票

试试这个
班级计划 { 静态无效主(字符串[]参数) {

        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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.