【问题标题】:Find the count of text files in a directory recursively [duplicate]递归查找目录中文本文件的数量[重复]
【发布时间】:2013-10-10 05:13:55
【问题描述】:

我正在尝试编写一些代码来计算目录及其子目录中的所有文本文件。我试过下面的代码:

private void button1_Click_1(object sender, EventArgs e)
{
    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
    DialogResult result = folderBrowserDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
        MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

要在文件夹及其子目录中搜索TXT文件,请使用:

string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.txt", SearchOption.AllDirectories);

【讨论】:

  • 谢谢.. 现在我可以过滤文本文件了..
【解决方案2】:

无需遍历目录。已经有一个 .NET 工具可以执行此操作。

要获取具有特定扩展名的文件列表,包括子目录,请使用,

var files = Directory.EnumerateFiles(srcDir, "*.txt", SearchOption.AllDirectories);

【讨论】:

    【解决方案3】:
    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
    DialogResult result = folderBrowserDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        int fileCount = GetFileCount(folderBrowserDialog1.SelectedPath);        
    }
    

    从父目录和所有子目录递归获取文本文件计数,

    private int GetFileCount(string s)
    {
        return Directory.GetFiles(s, "*.txt").Count() + Directory.GetDirectories(s).Select(GetFileCount).Sum();
    }
    

    【讨论】:

    • 很好的递归小函数,但GetFiles() 已经有第三个重载允许搜索子目录。
    • 我刚刚从其他答案中注意到。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2015-07-19
    • 2016-10-17
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多