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);
    }
相关推荐
csdn_aspnet4 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
C蔡博士7 小时前
Unity2D物理系统-从入门到实战优化
unity·游戏引擎·rigidbody2d
武藤一雄9 小时前
C# 设计模式大全(第一弹|7种)
microsoft·设计模式·微软·c#·.net·.netcore
格林威10 小时前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
向上的车轮11 小时前
熟悉C#如何转TypeScript——SDK与包引用
开发语言·typescript·c#
CSharp精选营12 小时前
Dispose 不释放?C# 资源泄漏的 3 种隐蔽场景排查
c#·资源泄漏
unicrom_深圳市由你创科技13 小时前
LabVIEW和C#在工业控制中的应用差异是什么?
fpga开发·c#·labview
mxwin14 小时前
Unity Shader 顶点动画:在顶点着色器中实现风吹草动、河流波动、布料模拟
unity·游戏引擎·shader·着色器
唐青枫14 小时前
C#.NET Consul + Steeltoe 深入解析:服务注册发现、健康检查与微服务接入
c#·.net
DowneyJoy15 小时前
【Unity3D补充知识点】常用数据结构分析-集合(List<T>)
数据结构·unity·c#·list