Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I am reading some files from a directory.
I jus want to sort it on the basis of creationDateTime.

Here is my code snippet:

C#
DirectoryInfo CHMReaderFolder = new DirectoryInfo("c:\\MyDir");
FileInfo[] DirFiles;
DirFiles = CHMReaderFolder.GetFiles("*.xml");


Now, I want to sort
DirFiles
on the basis of creationDateTime.

I am using .NET 2.0
Posted
Updated 1-May-12 20:11pm
v3

C#
void Main()
{
    DirectoryInfo CHMReaderFolder = new DirectoryInfo("c:\\MyDir");
    FileInfo[] DirFiles;
    DirFiles = CHMReaderFolder.GetFiles("*.xml");
    List<FileInfo> list = new List<FileInfo>(DirFiles);
    list.Sort(new Sorter());
}

class Sorter : IComparer<FileInfo>
{
#region IComparer<FileInfo> Members

public int Compare(FileInfo x, FileInfo y)
{
    return x.CreationTime.CompareTo(y.CreationTime);
}

#endregion
}
 
Share this answer
 
v4
Comments
Vipin_Arora 2-May-12 2:41am    
thanks John... Its working ....
That is more of a pain than it looks - the Array.Sort method uses the default IComparable implementation of FileInfo, and you can't override it in a derived class, because you can't easily cast up from the FileInfo returned by GetFiles!
You can do it with Linq:
C#
DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
FileInfo[] files = di.GetFiles("*.xml").OrderBy(fi => fi.CreationTime).ToArray();
But if you are using only .NET 2 that isn't so easy as Linq is not included.

Your only other option is to do it manually: either write your own sort method, or encapsulate the FileInfo into a different class and sort that.
 
Share this answer
 
you can do like this
C#
DataTable DtTable = new DataTable();
            DtTable.Columns.Add("filename", typeof(string));
            DtTable.Columns.Add("Created", typeof(DateTime));
            DirectoryInfo Diinfo = new DirectoryInfo(@"C:\WINDOWS\");
            FileInfo [] Finfo  = Diinfo.GetFiles();
           
            foreach (FileInfo fi in Finfo)
            {
               DataRow DrNewRow = DtTable.NewRow();
               DrNewRow["filename"] = fi.Name.ToString();
               DrNewRow["Created"] = fi.CreationTime;
               DtTable.Rows.Add(DrNewRow);
            }

            DataView dv = new DataView(DtTable);
            dv.Sort = "Created Asc";
            DataTable NewSortTable = dv.ToTable();
            dataGridView1.DataSource = NewSortTable;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900