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);
    }
相关推荐
唐青枫11 小时前
对象到底住在哪里?C#.NET 托管堆从分配、GC 到内存排查
c#·.net
fogota13 小时前
Emoji与Segoe MDL2 Assets的比较
c#·wpf
灸木14 小时前
C# 多线程与异步
c#
灸木15 小时前
Unity 多线程与并发:什么时候该用多线程?
unity
鱼听禅17 小时前
C# 学习笔记-使用 类型化客户端搭建HTTP客户端服务
学习·http·c#·工厂方法模式
淡海水18 小时前
11-02-Unity-Mono-vs-IL2CPP-两种脚本后端的数据结构行为差异
数据结构·unity·游戏引擎·il2cpp·mono
彧azz19 小时前
初学Unity:编辑器
笔记·学习·unity·游戏引擎
geovindu19 小时前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式
小小数媒成员20 小时前
GPU优化(1)
游戏·unity·游戏引擎