Getting Direcotry files sorted by date, is it possible?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I wondering if it possilble to get the directory files ordered by creation date

string [] files = System.IO.Directory.GetFiles(strPath,"*.msg")

can I sort the returned file by creation date?

or is there a ready method do the jobthat in .NET
 
Raed Sawalha said:
I wondering if it possilble to get the directory files ordered by creation date

string [] files = System.IO.Directory.GetFiles(strPath,"*.msg")

can I sort the returned file by creation date?

You need to implement your own IComparer do the specialized sort:

using System;
using System.IO;
using System.Collections;

public class SortFiles
{
public class CompareFileByDate :IComparer
{
int IComparer.Compare(Object a, Object b)
{
FileInfo fia = new FileInfo((string)a);
FileInfo fib = new FileInfo((string)b);

DateTime cta = fia.CreationTime;
DateTime ctb = fib.CreationTime;

return DateTime.Compare(cta, ctb);
}
}

public static void Main()
{
string [] files = System.IO.Directory.GetFiles("..");

IComparer fileComparer = new CompareFileByDate();
Array.Sort(files, fileComparer);

foreach ( string f in files )
{
Console.WriteLine(f);
}

}
}

/J\
 
Another way is this one (no need of an extra class):

// get your files (names)
string[] fileNames = Directory.GetFiles("c:\\Temp\\", "*.*");

// Now read the creation time for each file
DateTime[] creationTimes = new DateTime[fileNames.Length];
for (int i=0; i < fileNames.Length; i++)
creationTimes = new FileInfo(fileNames).CreationTime;

// sort it
Array.Sort(creationTimes,fileNames);

// and print for test
Console.WriteLine("Files ordered by creation time");
for (int i=0; i < fileNames.Length; i++)
Console.WriteLine("{0}: {1}", creationTimes, fileNames);


HTH,
Stefan
 
Back
Top