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);
    }
相关推荐
kaikaile199517 分钟前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿41 分钟前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
rit84324991 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
在路上看风景5 小时前
15. 纹理尺寸是4的倍数
unity
白衣衬衫 两袖清风6 小时前
ABP框架+Dapper执行原生sql
sql·c#·.net
在路上看风景7 小时前
1.15 并行编程
c#
chao1898447 小时前
基于C# WinForm实现的仿微信打飞机游戏
游戏·微信·c#
AT~8 小时前
unity 使用Socket和protobuf实现网络连接
unity·游戏引擎
wearegogog1238 小时前
C# 条码打印程序(一维码 + 二维码)
java·开发语言·c#
sali-tec8 小时前
C# 基于halcon的视觉工作流-章69 深度学习-异常值检测
开发语言·图像处理·算法·计算机视觉·c#