按日期排序文件

时间:2011-02-19 06:09:02

标签: c# .net

我正在使用此类代码来比较文件以按日期排序..

FileInfo f = new FileInfo(name1);
FileInfo f1 = new FileInfo(name2);
if (f.Exists && f1.Exists)
   output = DateTime.Compare(f.LastWriteTime, f1.LastWriteTime);

有没有更好更快的方法按日期排序?

我一次只能比较2个项目......

我无法从目录中获取所有文件。

8 个答案:

答案 0 :(得分:54)

您可以使用LINQ:

var sortedFiles = new DirectoryInfo(@"D:\samples").GetFiles()
                                                  .OrderBy(f => f.LastWriteTime)
                                                  .ToList();

答案 1 :(得分:11)

    DirectoryInfo directoryInfo = new DirectoryInfo(@"D:\Temp");
    var result = directoryInfo.GetFiles("*.*",SearchOption.AllDirectories).OrderBy(t => t.LastWriteTime).ToList();

答案 2 :(得分:9)

使用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);

答案 3 :(得分:4)

这是为整个目录执行此操作的另一种方法: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);
}

您需要一个实现IComparer的新DateCompareFileInfo类:

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;
    }
}

答案 4 :(得分:3)

重要 - 当通过LastWriteTime进行排序时,应该注意的是,如果文件从未被修改过,则此日期可能会返回1601或1600.这是MSDN所说的:

  

如果path参数中描述的文件不存在,则此方法返回美国俄勒冈州公元1601年1月1日午夜12点,协调世界时(UTC),调整为当地时间。

如果您的时区是PST,那么日期实际上是12/31/1600。为了解决这个问题并编写更强大的代码,您可以考虑这样的事情:

.OrderByDescending(f => f.LastWriteTime.Year <= 1601 ? f.CreationTime : f.LastWriteTime)

答案 5 :(得分:0)

这会将结果转换为SSIS对象的可读类:

var directory = Dts.Variables["User::SourceDir"].Value.ToString();
DirectoryInfo directoryInfo = new DirectoryInfo(directory);
var result = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories).OrderBy(t => t.LastWriteTime).ToList();
DataTable dsSorted = new DataTable();

DataColumn dc = new DataColumn("Value");
dsSorted.Columns.Add(dc);
foreach (FileInfo item in result)
{
    DataRow dr = dsSorted.NewRow();
    dr[0] = directory  + item ;
    dsSorted.Rows.Add(dr);
}

// lastModified = file.LastWriteTime;
Dts.Variables["User::FileNamesSorted"].Value = dsSorted;

// MessageBox.Show(Dts.Variables["User::FileNamesSorted"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;

答案 6 :(得分:0)

这是我从MSDN Social找到的解决方案。

DirectoryInfo di = new DirectoryInfo(@"c:\my-directory");
FileInfo[] files = di.GetFiles(@"*.*");
Array.Sort(files, (x, y) => Comparer<DateTime>.Default.Compare(x.LastWriteTime, y.LastWriteTime));

答案 7 :(得分:0)

// Compare LastWriteTimeUtc of FileInfos
private class FileInfoDateComparer : IComparer<FileInfo> {
    //
    public long direction = 1;
    //
    public FileInfoDateComparer( bool ascending ) {
        direction = ascending ? 1 : -1;
    }
    //
    public int Compare( FileInfo fi1, FileInfo fi2 ) {
        long d = direction * ( fi1.LastWriteTimeUtc.Ticks - fi2.LastWriteTimeUtc.Ticks );
        return d < 0 ? -1 : d > 0 ? 1 : 0;
    }
}
//
//
private static FileInfo[] SortByDate( FileInfo[] afi, bool ascending ) {
    if ( null != afi ) {
        if ( 0 < afi.Length ) {
            var c = new FileInfoDateComparer( ascending );
            Array.Sort( afi, c );
        }
    }
    return afi;
}