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);
    }
相关推荐
唐青枫2 小时前
C#.NET YARP 跨域配置详解:网关统一处理 CORS
c#·.net
程序leo源4 小时前
Qt信号与槽深度详解
c语言·开发语言·数据库·c++·qt·c#
598866753@qq.com7 小时前
Unity Job System笔记
unity
winlife_8 小时前
Funplay Unity MCP 与 Unity AI Assistant 详细对比:开源 MCP 工具集 vs 官方全栈 AI 产品
人工智能·unity·开源·ai编程·claude·mcp
御水流红叶9 小时前
Android-Unity游戏逆向思路
android·游戏·unity
yoyo_zzm9 小时前
四大编程语言对比:C/C++/C#/PHP
c++·c#·php
weixin_4280053010 小时前
C#调用 AI学习从0开始-第1阶段(基础与工具)-第4天CoT思维链学习
开发语言·学习·ai·c#·cot
ellis197010 小时前
Unity图集Atlas
unity
政沅同学10 小时前
C# TCP通讯(客户端)
网络·tcp/ip·c#
思麟呀11 小时前
在C++基础上理解CSharp-3
开发语言·c++·c#