0
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");
    }
}

This counts number of files in folder. But I need count for only specific files which are in folder such a .txt or .mp3

pbaris
  • 4,525
  • 5
  • 37
  • 61
dumbCoder
  • 5
  • 3
  • 1
    possible duplicate of [Find a file with a certain extension in folder](http://stackoverflow.com/questions/3152157/find-a-file-with-a-certain-extension-in-folder) – cbr Apr 20 '15 at 14:42
  • If you prefix your code with 4 spaces, it will format nicely. – Ulric Apr 20 '15 at 14:42

3 Answers3

1
DirectoryInfo di = new DirectoryInfo(@"C:/temp");

di.GetFiles("test?.txt").Length;

or

di.GetFiles("*.txt").Length;
Dominic Scanlan
  • 1,009
  • 1
  • 6
  • 12
1

Check if the files' extensions are in your specified collection:

 var validExts = new []{".txt", ".mp3"};

 string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath)
            .Where(f => validExts.Contains(Path.GetExtension(f)))
            .ToArray();
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

Just union the different extensions:

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

you can chain as many Union as you want. In case you just want to count the files you don't have to use any 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")
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215