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

2
  • 1
    possible duplicate of Find a file with a certain extension in folder Commented Apr 20, 2015 at 14:42
  • If you prefix your code with 4 spaces, it will format nicely. Commented Apr 20, 2015 at 14:42

3 Answers 3

1
DirectoryInfo di = new DirectoryInfo(@"C:/temp"); di.GetFiles("test?.txt").Length; 

or

di.GetFiles("*.txt").Length; 
Sign up to request clarification or add additional context in comments.

Comments

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(); 

2 Comments

HashSet<String> for validExts instead of String[] IMHO looks better.
sure that's better. But the change is probably insignificant on this scale.
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") } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.