获取文件的md5码.md 1.4 KB

#unity/日常积累

可以理解为,文件的其中一个标识量;

文件内容如果修改保存了,md5码就会变;
如果文件是通过同一个工具生成,在生成前没修改的前提下,就算把文件删除了,再重新生成该文件,md5码也是不会变的;

所以可以用来,判断一个文件是否进行了内容的修改;

![[Pasted image 20220426100956.png]]

using System.IO;
using System.Security.Cryptography;
using UnityEngine;


public static class MD5Util
{
    public static Hash128 File(string file)
    {
        try
        {
            FileStream fileStream = new FileStream(file, FileMode.Open);
            byte[] hash = new MD5CryptoServiceProvider().ComputeHash((Stream) fileStream);
            fileStream.Close();
            return new Hash128(MD5Util.ToMD5(hash[0], hash[1], hash[2], hash[3]), 
                MD5Util.ToMD5(hash[4], hash[5], hash[6], hash[7]),
                MD5Util.ToMD5(hash[8], hash[9], hash[10], hash[11]), 
                MD5Util.ToMD5(hash[12], hash[13], hash[14], hash[15]));
        }
        catch
        {
            return new Hash128();
        }
    }

    private static uint ToMD5(byte first, byte second, byte third, byte fourth)
    {
        return (uint) ((int) first + ((int) second << 8) + ((int) third << 16) + ((int) fourth << 24));
    }
}

测试:

![[Pasted image 20220426092021.png]]

结果:

![[Pasted image 20220426092034.png]]