C#如何判断文件是否相同?

自己写了一个整理音乐文件的小工具。

加载文件的时候,需要判断是否为同一文件。前面的做法是,每次加载文件的时候都去检测文件的MD5。这种方式比较保险,但是造成的影响是加载的时候会比较慢,特别是文件比较多的时候。

其实大部分的时候,这些都是同样的文件,而且也没有变化。

所以想通过其它比较快捷的方式先判断是否为同一文件,然后再去判断有无必要重新检测MD5判断。

目前的判断逻辑是,如果文件的完整路径,文件大小,创建时间,修改时间都一致,那就认为是同一个文件。

个人认为这4种属性都一模一样,但是文件又不相同的情况,概念会非常小。

下面是我用到的数据类:

using Prism.Mvvm;
using CgdataBase;
using FreeSql.DataAnnotations;
using System.IO;
using System;

namespace MusicManager.Models
{
    [Table(Name = "mm_file_md5")]
    public class FileMd5Info : BindableBase, IBaseInfo
    {
        [Column(IsIdentity = true, IsPrimary = true)]
        public int ID { get; set; }

        [Column(IsIgnore = true)]
        public string FileName { get; set; }

        [Column(IsIgnore = true)]
        public string FullPath { get; set; }

        [Column(IsIgnore = true)]
        public long Length { get; private set; }

        [Column]
        public DateTime CreationTime { get; private set; }

        [Column]
        public DateTime LastWriteTime { get; private set; }

        [Column(IsNullable = false)]
        public string MD5 { get; set; }

        public FileMd5Info()
        {
        }

        public FileMd5Info(string filePath)
        {
            var info = new FileInfo(filePath);
            FullPath = info.FullName;
            Length = info.Length;
            CreationTime = info.CreationTime;
            LastWriteTime = info.LastWriteTime;
        }

        public bool IsDifferent(FileMd5Info info)
        {
            return info.FullPath != FullPath || info.Length != Length || info.CreationTime != CreationTime || info.LastWriteTime != LastWriteTime;
        }
    }
}

 

posted @ 2022-05-31 09:46  wzwyc  阅读(836)  评论(0编辑  收藏  举报