Env: C#, VStudio 2013, 4.5 Framework, Winforms
Goal : Getting the number of files (Count) in a folder and subfolder that match extensions stored in an array of string. The array of extension can be with the "." of not. {".dat","txt",".msg"}
What i've done so far : When I'm having the "." in the array of extensions, everything is working : {".dat",".txt",".msg"}
I have tried the Replace but it's always returning 0.
The working code (Only if always with the "." in array of string):
string[] ext= new string[] { ".txt", ".msg", ".dat" };
totalFilesInTN = Directory.EnumerateFiles(dlg1.SelectedPath, "*.*", SearchOption.AllDirectories)
.Count(s => ext.Any(s1 => s1 == Path.GetExtension(s)));
The not working code (always return 0) :
string[] ext= new string[] { "txt", ".msg", "dat" };
totalFilesInTN = Directory.EnumerateFiles(dlg1.SelectedPath, "*.*", SearchOption.AllDirectories)
.Count(s => ext.Any(s1 => s1 == Path.GetExtension(s).Replace(".", "")));
To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1. It doesn't count dotfiles.
Right-click on the folder and select the “Properties” option. The “Properties” window will open and you will be able to see the number of files and subdirectories located in the directory selected.
Approach: The characters can be counted easily by reading the characters in the file using getc() method. For each character read from the file, increment the counter by one.
The documentation for the Path.GetExtension
method states that the return value is:
The extension of the specified path (including the period "."), or null, or String.Empty.
Your second block of code strips off the '.' so none of the elements will match. Therefore, go the opposite way with your list of extensions and just ensure that the start of each extension has a '.' and then use your first block of code.
string[] ext = new string[] {"txt", ".msg", ".dat" }
.Select(x => x.StartsWith(".") ? x : "." + x)
.ToArray();
You need to replace the .
dot in both the array ext
element and the directory item. You need to use .Replace with s1
as well to compare the array and file extension after removing dot from each.
string[] ext= new string[] { "txt", ".msg", "dat" };
totalFilesInTN = Directory.EnumerateFiles(dlg1.SelectedPath, "*.*", SearchOption.AllDirectories)
.Count(s => ext.Any(s1 => s1.Replace(".", "") == Path.GetExtension(s).Replace(".", "")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With