dumbCoder
dumbCoder

Reputation: 5

Count specific files from folder

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

Upvotes: 0

Views: 1015

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

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

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

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

Upvotes: 1

Dominic Scanlan
Dominic Scanlan

Reputation: 1009

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

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

or

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

Upvotes: 1

Related Questions