I need to count the number of excel files,pdf files from a directory.
I have 开发者_Go百科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?
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)));
Use SearchPattern in GetFiles
method.
dir.GetFiles("*.XLS");
int count = 0;
foreach (string file in Directory.GetFiles(@"D:\"))
{
if (file.EndsWith(".pdf") || file.EndsWith(".xls"))
{
count++;
}
}
String[] excelFiles=Directory.GetFiles("C:\\", "*.xls");
int count = Directory.GetFiles(path).Count(f =>(f.EndsWith(".xls") || f.EndsWith(".xlsx")));
simple
int count = dir.GetFiles("*.txt").Length + dir.GetFiles("*.pdf").Length
var count = System.IO.Directory.GetFiles(@"D:\")
.Count(p => Path.GetExtension(p) == ".xls");
精彩评论