I am using such code to compare files to sort by date..
FileInfo f = new FileInfo(name1);
FileInfo f1 = new FileInfo(name2);
if (f.Exists && f1.Exists)
output = DateTime.Compare(f.LastWriteTime, f1.LastWriteTime);
Is there any better and faster way to sort by Date?
At a time i can compare only 2 items...
I could not sort by getting all files from directory.
Click the sort option in the top right of the Files area and select Date from the dropdown. Once you have Date selected, you will see an option to switch between descending and ascending order.
Simply select the 'Edit Details' option and select 'Show Document Date on Screen'. Arrange Documents Chronologically. Sorting document in date order can be done with a single click. Select the arrow icon to sort either ascending or descending order.
You can use LINQ:
var sortedFiles = new DirectoryInfo(@"D:\samples").GetFiles()
.OrderBy(f => f.LastWriteTime)
.ToList();
DirectoryInfo directoryInfo = new DirectoryInfo(@"D:\Temp");
var result = directoryInfo.GetFiles("*.*",SearchOption.AllDirectories).OrderBy(t => t.LastWriteTime).ToList();
What about using Array.Sort ?
string[] fileNames = Directory.GetFiles("directory ", "*.*");
DateTime[] creationTimes = new DateTime[fileNames.Length];
for (int i = 0; i < fileNames.Length; i++)
creationTimes[i] = new FileInfo(fileNames[i]).CreationTime;
Array.Sort(creationTimes, fileNames);
This is another way of doing it for the whole directory:dateCompareFileInfo
if (Directory.Exists(DIRECTORY_NAME))
{
DirectoryInfo di = new DirectoryInfo(DIRECTORY_NAME);
FileInfo[] logFiles = di.GetFiles("AN-10-log.txt*");
DateCompareFileInfo dateCompareFileInfo = new DateCompareFileInfo();
Array.Sort(logFiles, dateCompareFileInfo);
}
And the you need a new DateCompareFileInfo class that implements IComparer:
class DateCompareFileInfo : IComparer<FileInfo>
{
/// <summary>
/// Compare the last dates of the File infos
/// </summary>
/// <param name="fi1">First FileInfo to check</param>
/// <param name="fi2">Second FileInfo to check</param>
/// <returns></returns>
public int Compare(FileInfo fi1, FileInfo fi2)
{
int result;
if (fi1.LastWriteTime == fi2.LastWriteTime)
{
result = 0;
}
else if (fi1.LastWriteTime < fi2.LastWriteTime)
{
result = 1;
}
else
{
result = -1;
}
return result;
}
}
IMPORTANT - When ordering by LastWriteTime, it should be noted that if the file has never been modified, this date may return 1601 or 1600. Here is what MSDN says:
If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
If your timezone is PST, like me the date will actually be 12/31/1600. To get around this and write more robust code you might consider something like this:
.OrderByDescending(f => f.LastWriteTime.Year <= 1601 ? f.CreationTime : f.LastWriteTime)
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