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);
    }
相关推荐
合作小小程序员小小店1 小时前
桌面开发,在线%超市销售管理%系统,基于vs2022,c#,winform,sql server数据
开发语言·数据库·microsoft·c#
p***32353 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
2501_941807264 小时前
Java高性能消息队列与Kafka实战分享:大规模消息处理、异步通信与性能优化经验
c#·linq
周杰伦fans5 小时前
C# 中的**享元工厂**模式
开发语言·数据库·c#
鹿衔`5 小时前
通过Flink 1.19 客户端实现Flink集群连接 Kafka 基础测试报告
c#·linq
龙智DevSecOps解决方案5 小时前
Perforce《2025游戏技术现状报告》Part 1:游戏引擎技术的广泛影响以及生成式AI的成熟之路
人工智能·unity·游戏引擎·游戏开发·perforce
玩泥巴的7 小时前
.NET 8+ 飞书API实战:自动化群组管理与消息推送
c#·.net·二次开发·飞书
烛阴7 小时前
从`new`关键字开始:精通C#类与对象
前端·c#
yangshuquan8 小时前
使用 C# + IronOcr,轻松实现图片文字自动识别(OCR)和提取
c#·ocr·编程技巧·winforms
天天代码码天天8 小时前
TSR18测速雷达C#对接
c#·雷达测速·tsr18测速雷达