Directory.GetFiles如何访问子目录?

时间:2013-10-03 13:55:57

标签: c# winforms

如何从子目录中获取文件,使用此代码只能为列出的目录下的文件完成工作:

    DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
    Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output");

foreach (FileInfo d in selDir.GetFiles())
    {
        //my code
    }

4 个答案:

答案 0 :(得分:4)

var allFiles = selDir.GetFiles("*.*", SearchOption.AllDirectories);

答案 1 :(得分:2)

您拥有所需文件夹的DirectoryInfo,因此遍历其所有目录,然后您可以获取每个文件的文件。

DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
Directory.CreateDirectory(Path.Combine(folderBrowserDialog1.SelectedPath, "Output"));

foreach (string dir in System.IO.Directory.GetDirectories(selDir.FullName, "*.*", System.IO.SearchOption.AllDirectories))
{
    foreach (string file in Directory.GetFiles(dir))
    {
        //my code
    }
}

答案 2 :(得分:2)

我通常会做一个反复出现的方法。例如:

    private void getFiles(string directory)
    {
        string[] files = Directory.GetFiles(directory);
        string[] directories = Directory.GetDirectories(directory);

        foreach (string file in files)
        {
            // Code here.
        }

        foreach (string subDirectory in directories)
        {
            // Call the same method on each directory.
            getFiles(subDirectory);
        }
    }

答案 3 :(得分:1)

DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output");

string[] files = Directory.GetFiles(selDir.FullName, "*.*", SearchOption.AllDirectories);

foreach (string file in files)
{
    // your code
}