繁体   English   中英

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

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

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

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()并用路径“填充”列表,但我希望能够多次使用它来创建具有不同目录等的不同列表。

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

 Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)
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

只需使用:

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

你可以使用这样的东西:

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

而不是使用“ ”你可以输入文件的名称或只是类型“* .txt”,SearchOption.AllDirectories是搜索所有子文件夹,你可以改变,如果你只想要一个更多的关于如何使用它在这里

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

private List<string> DirSearch(string sDir)

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

return files;

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

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



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

试试这个
class 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;
    }
}

一个LINQ解决方案:

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

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM