haelenb@bellsouth.net
12/24/2002 3:12:00 AM
Hi Avi,
You can store the FileInfo Object in a SortedList, and provide a Comparer
Object that does the
correct comparison.
Code Below:
using System;
using System.IO;
using System.Collections;
namespace SortedDirList
{
class Class1
{
static void Main(string[] args)
{
Class1 instance = new Class1();
instance.PrintFilesByDate();
}
public void PrintFilesByDate()
{
DateComparer dateComparer = new DateComparer();
DirectoryInfo dirInfo = new DirectoryInfo(@"c:\temp");
FileInfo[] fileInfos = dirInfo.GetFiles("*.txt");
SortedList sortedList = new SortedList(dateComparer);
foreach (FileInfo fi in fileInfos)
{
sortedList.Add(fi, fi);
}
foreach(DictionaryEntry entry in sortedList)
{
FileInfo fi = entry.Value as FileInfo;
Console.WriteLine("Name: {0}, Date: {1}",
fi.Name, fi.LastAccessTime.ToLongTimeString());
}
}
class DateComparer : IComparer
{
#region implementation of icomparer
public int Compare(object x, object y)
{
FileInfo fiX = x as FileInfo;
FileInfo fiY = y as FileInfo;
DateTime datex = fiX.LastAccessTime;
DateTime datey = fiY.LastAccessTime;
if (datex == datey)
return 0;
else if (datex < datey)
return -1;
else
return +1;
}
#endregion
}
}
}
"Avi" <atreistm@netvision.net.il> wrote in message
news:OwzNg2sqCHA.1636@TK2MSFTNGP12...
> I am trying to write a routine that will search for a set of files in a
> directory and return a sorted container of files. For instance, I would
like
> to search for all files starting with the string "test" in directory
> "c:\mytest" and return a sorted list of files by date in descending order.
>
> I have tried the following code:
> DirectoryInfo di = new DirectoryInfo(@"c:\mytest\");
>
>
> FileSystemInfo[] fiArr = di.GetFileSystemInfos("test*.*");
>
> // print out the names of the files
>
> foreach (FileSystemInfo fri in fiArr)
>
> Console.WriteLine(fri.FullName);
>
> This code returns a list of the files matching test*.*, however the list
is
> in alphabetical order, not date sorted. I can find no options to pass
> GetFileSystemInfos a sort order.
>
> Any suggestions as to how to code this within the Framework would be
> appreciated.
>
>