Sorting the result of Directory.GetFiles in C#
Very easy with LINQ. To sort by name, var sorted = Directory.GetFiles(“.”).OrderBy(f => f); To sort by size, var sorted = Directory.GetFiles(“.”).OrderBy(f => new FileInfo(f).Length);
Very easy with LINQ. To sort by name, var sorted = Directory.GetFiles(“.”).OrderBy(f => f); To sort by size, var sorted = Directory.GetFiles(“.”).OrderBy(f => new FileInfo(f).Length);
Have you tried EnumerateFiles method of DirectoryInfo class? As MSDN Says The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned; when you use GetFiles, you must wait for the whole array of FileInfo objects to be returned … Read more
It looks like the glob npm package would help you. Here is an example of how to use it: File hierarchy: test ├── one.html └── test-nested └── two.html JS code: const glob = require(“glob”); var getDirectories = function (src, callback) { glob(src + ‘/**/*’, callback); }; getDirectories(‘test’, function (err, res) { if (err) { console.log(‘Error’, … Read more
If you would like to do your filtering in LINQ, you can do it like this: var ext = new List<string> { “jpg”, “gif”, “png” }; var myFiles = Directory .EnumerateFiles(dir, “*.*”, SearchOption.AllDirectories) .Where(s => ext.Contains(Path.GetExtension(s).TrimStart(“.”).ToLowerInvariant())); Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for … Read more
You will have to do the recursion manually; don’t use AllDirectories – look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array): using System; using System.IO; static class Program { static void Main() { string path = “”; … Read more
You can use System.IO.Path.GetFileName to do this. E.g., string[] files = Directory.GetFiles(dir); foreach(string file in files) Console.WriteLine(Path.GetFileName(file)); While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo … Read more
Why not create an extension method? That’s more readable. public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException(“extensions”); IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>(); foreach(string ext in extensions) { files = files.Concat(dir.GetFiles(ext)); } return files; } EDIT: a more efficient version: public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] … Read more