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);
    }
相关推荐
A_nanda10 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
码云数智-园园12 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#
PfCoder13 小时前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
JIes__15 小时前
Unity(二)——核心系统
unity·游戏引擎
gc_229915 小时前
C#学习调用OpenMcdf模块解析ole数据的基本用法(1)
c#·ole·openmcdf
独处东汉15 小时前
freertos开发空气检测仪之按键输入事件管理系统设计与实现
人工智能·stm32·单片机·嵌入式硬件·unity
天人合一peng19 小时前
Unity 中 Text-TextMeshPro的获取与赋值
unity·游戏引擎
MM_MS20 小时前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
老骥伏枥~21 小时前
C# 控制台:Console.ReadLine / WriteLine
开发语言·c#
PfCoder1 天前
C#中定时器之System.Timers.Timer
c#·.net·visual studio·winform