1

I need to count the number of excel files,pdf files from a directory.

I have Counted the total number of files from a directory using

 System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"D:\");
 int count = dir.GetFiles().Length; 

Any Suggestion?

bala3569
  • 10,832
  • 28
  • 102
  • 146

7 Answers7

5

Here's a LINQ solution.

var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
    ".xls",
    ".xlsx",
    ".pdf",
};
var baseDir = @"D:\";
var count = Directory.EnumerateFiles(baseDir)
                     .Count(filename =>
                                extensions.Contains(Path.GetExtension(filename)));
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • 1
    +1 nice use of EnumerateFiles. Also "why wouldn't it ever be possible" made me smile. – Conrad Frix May 27 '11 at 05:52
  • @Conrad: Yeah, it's just one of those things that always gets to me. It always strikes a nerve when I hear the words, "is it possible?" when there are tools we use every day that does "the impossible." But that part is gone now. :) – Jeff Mercado May 27 '11 at 11:23
2

Use SearchPattern in GetFiles method.

dir.GetFiles("*.XLS");
Umesh CHILAKA
  • 1,466
  • 14
  • 25
1
int count = 0;
foreach (string file in Directory.GetFiles(@"D:\"))
{
    if (file.EndsWith(".pdf") || file.EndsWith(".xls"))
    {
        count++;
    }
}
aligray
  • 2,812
  • 4
  • 26
  • 35
0
   var count = System.IO.Directory.GetFiles(@"D:\")
               .Count(p => Path.GetExtension(p) == ".xls");
Zach Johnson
  • 23,678
  • 6
  • 69
  • 86
Aravind
  • 4,125
  • 1
  • 28
  • 39
  • can you compare strings like that? Shouldn't be .Equals()? – surfen May 27 '11 at 05:44
  • 1
    @surfen: if it were Java it would need to be `.equals()`; but in C# it doesn't matter. See http://stackoverflow.com/questions/1659097/c-string-equals-vs – Zach Johnson May 27 '11 at 05:47
0
String[] excelFiles=Directory.GetFiles("C:\\", "*.xls");
crypted
  • 10,118
  • 3
  • 39
  • 52
0
int count = Directory.GetFiles(path).Count(f =>(f.EndsWith(".xls") || f.EndsWith(".xlsx")));
abhilash
  • 5,605
  • 3
  • 36
  • 59
0

simple

int count = dir.GetFiles("*.txt").Length + dir.GetFiles("*.pdf").Length
Binil
  • 6,445
  • 3
  • 30
  • 40