Unity - C#比较两个文件是否相同

前言:我的情况是需要检测目标目录文件在发生变动时,将其拷贝至另一个目录

Hash比较法

复制代码
	static bool CompareFileHash(string sourcePath, string targetPath)
	{
        // 目标文件不存在,则返回不相同
		if (!File.Exists(targetPath))
			return false;

		string getHash(string filePath)
		{
			using (var md5 = MD5.Create())
			using (var stream = File.OpenRead(filePath))
			{
				byte[] hashBytes = md5.ComputeHash(stream);
				return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
			}
		}
		var hash1 = getHash(sourcePath);
		var hash2 = getHash(targetPath);
		Debug.Log($"{sourcePath}|{hash1}\n{targetPath}|{hash2}");
		return hash1 == hash2;
	}

增加文件长度比较

复制代码
    public static bool CompareFile(string sourcePath, string targetPath)
    {
        if (!File.Exists(targetPath))
            return false;
            
        FileInfo sourceInfo = new FileInfo(sourcePath);
        FileInfo targetInfo = new FileInfo(targetPath);
        
        if (sourceInfo.Length != targetInfo.Length)
            return false;
        
        return CompareFileHash(sourcePath,targetPath);
    }
相关推荐
c#上位机44 分钟前
wpf之命令
c#·wpf
曹牧4 小时前
C#:函数默认参数
开发语言·c#
R-G-B13 小时前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长13 小时前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
Aevget15 小时前
DevExpress WinForms v25.1亮点 - PDF Viewer(查看器)等全新升级
pdf·c#·界面控件·winform·devexpress·ui开发
InCerry15 小时前
为 .NET 10 GC(DATAS)做准备
性能优化·c#·.net·gc
future_studio16 小时前
聊聊 Unity(小白专享、熟悉基础编程 ... ...)
unity·游戏引擎
曹牧16 小时前
C#:可选参数
开发语言·c#
Sunsets_Red19 小时前
差分操作正确性证明
java·c语言·c++·python·算法·c#
Aevget19 小时前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(一)
c#·wpf·界面控件·devexpress·ui开发