-1

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

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

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

4 回答 4

4
var allFiles = selDir.GetFiles("*.*", SearchOption.AllDirectories);
于 2013-10-03T14:04:58.363 回答
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
    }
}
于 2013-10-03T14:03:11.527 回答
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);
        }
    }
于 2013-10-03T14:14:32.247 回答
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
}
于 2013-10-03T13:57:47.960 回答