I have this code to list all the files in a directory.
class GetTypesProfiler
{
static List<Data> Test()
{
List<Data> dataList = new List<Data>();
string folder = @"DIRECTORY";
Console.Write("------------------------------------------\n");
var files = Directory.GetFiles(folder, "*.dll");
Stopwatch sw;
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
var fileinfo = new FileInfo(file);
long fileSize = fileinfo.Length;
Console.WriteLine("{0}/{1}", fileName, fileSize);
}
return dataList;
}
static void Main()
{
...
}
}
I need to print out the file info based on file size or alphabetical order. How can I sort the result from Directory.GetFiles()?
Very easy with LINQ.
To sort by name,
To sort by size,
To order by date: (returns an enumerable of FileInfo):
or, to order by name:
Making
FileInfo
instances isn't necessary for ordering by file name, but if you want to apply different sorting methods on the fly it's better to have your array ofFileInfo
objects in place and then justOrderBy
them byLength
orName
property, hence this implementation. Also, it looks like you are going to createFileInfo
anyway, so it's better to have a collection ofFileInfo
objects either case.Sorry I didn't get it right the first time, should've read the question and the docs more carefully.
You can use LINQ if you like, on a FileInfo object: