开发者

problem with comparing two files based on datetime upto minute?

开发者 https://www.devze.com 2023-01-30 06:20 出处:网络
If i compare two files without rounding upto minute result for these queries var queryList1Only3 = (from file in list1 select file).Except(list2, myFileCompare2);

If i compare two files without rounding upto minute result for these queries

var queryList1Only3 = (from file in list1 select file).Except(list2, myFileCompare2);
var queryList1Only3开发者_运维知识库3 = (from file in list2 select file).Except(list1, myFileCompare2);

are

12/14/2010 4:14:10 PM     C:\xml\Tracker.xml
10/13/2010 3:00:27 PM      D:\xml\Tracker.xml

But if i round the datetime upto minute the result for queryList1Only3 is

   12/14/2010 4:14:10 PM     C:\xml\Tracker.xml

and second query returns nothing but empty because i have modified that C:\xml\Tracker.xml file only..and the other file is without changes...

and

public class FileCompareLastwritetime : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
        {
            public FileCompareLastwritetime() { }
            public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
            {
                return RoundToMinute(f1.LastWriteTime) == RoundToMinute(f2.LastWriteTime);
            }
            public int GetHashCode(System.IO.FileInfo fi)
            {
               return RoundToMinute(fi.LastWriteTime).GetHashCode();
            }
        }


 public static DateTime RoundToMinute(DateTime time)
            {
                return new DateTime(time.Year, time.Month, time.Day,
                                    time.Hour, time.Minute, 0, time.Kind);
            }

Any suggestion??

EDIT:

   IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
   IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories);


DateTime equals compares Ticks which can be slightly different when setting the values using time.Year, time.Month, etc. The best DateTime truncation method I have found is the following:

///<summary>
/// Extension methods for DateTime class
///</summary>
public static class DateTimeExt
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static System.DateTime Truncate(this System.DateTime date, long resolution)
    {
        return new System.DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

Usage: myDateTime.Truncate(TimeSpan.TicksPerMinute) to truncate to minutes. It does not round but neither does your example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号