通过CreationTime进行文件排序 [英] Files order by CreationTime
本文介绍了通过CreationTime进行文件排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从目录中读取一些文件.
我很想根据creationDateTime对它进行排序.
这是我的代码段:
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:
DirectoryInfo CHMReaderFolder = new DirectoryInfo("c:\\MyDir");
FileInfo[] DirFiles;
DirFiles = CHMReaderFolder.GetFiles("*.xml");
现在,我想在creationDateTime的基础上对
Now, I want to sort
DirFiles
进行排序.
我正在使用.NET 2.0
on the basis of creationDateTime.
I am using .NET 2.0
推荐答案
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
}
这比看起来要痛苦得多-Array.Sort方法使用FileInfo的默认IComparable实现,并且您无法覆盖它在派生类中,因为您不能轻易地从GetFiles返回的FileInfo中进行转换!
您可以使用Linq:
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:
DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
FileInfo[] files = di.GetFiles("*.xml").OrderBy(fi => fi.CreationTime).ToArray();
但是,如果您只使用.NET 2,那么它不那么容易,因为不包含Linq.
您唯一的其他选择是手动执行此操作:编写您自己的sort方法,或将FileInfo封装到另一个类中并对其进行排序.
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.
您可以像这样
you can do like this
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;
这篇关于通过CreationTime进行文件排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文