【问题标题】:Count specific files from folder计算文件夹中的特定文件
【发布时间】:2015-06-27 08:39:25
【问题描述】:
private void button1_Click(object sender, EventArgs e) {
    DialogResult result = folderBrowserDialog1.ShowDialog();
    if (result == DialogResult.OK) {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
        MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

这会计算文件夹中的文件数。但我只需要计算文件夹中的特定文件,例如 .txt.mp3

【问题讨论】:

标签: c# .net


【解决方案1】:

只是联合不同的扩展:

String[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.txt")
          .Union(Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.mp3"))
          .ToArray();

您可以根据需要链接任意数量的Union。如果您只想 count 不必使用任何 array 的文件:

private void button1_Click(object sender, EventArgs e) {
  if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
    MessageBox.Show(Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.txt")
             .Union(Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.mp3"))
             .Count(), 
      "Message")
}

【讨论】:

    【解决方案2】:

    检查文件的扩展名是否在您指定的集合中:

     var validExts = new []{".txt", ".mp3"};
    
     string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath)
                .Where(f => validExts.Contains(Path.GetExtension(f)))
                .ToArray();
    

    【讨论】:

    • HashSet<String> for validExts 而不是 String[] 恕我直言看起来更好。
    • 确定这样更好。但这种变化在这种规模上可能是微不足道的。
    【解决方案3】:
    DirectoryInfo di = new DirectoryInfo(@"C:/temp");
    
    di.GetFiles("test?.txt").Length;
    

    di.GetFiles("*.txt").Length;
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2015-01-07
      • 1970-01-01
      相关资源
      最近更新 更多