【參考原文】河樂不爲-Unity3D 學習筆記7 —— 獲取熱更新資源文件的MD5碼
概要
在熱更新時通過文件MD5碼比對來判斷文件是否更新,假如MD5碼不一致則可以判定文件發生了變化,所以需要進行更新。因此,需要爲那些能夠進行熱更新的文件生成對應的MD5碼,每個文件都對應唯一的一個MD5碼。
生成步驟
- 讀取文件流
- 讀取文件流中的字節數據
- 通過MD5接口生成MD5碼(獲得的是一個Hash字節數組)
- 將步驟3獲得的Hash字節數組轉換爲字符創
關鍵代碼:
public static string getFileHash(string filePath)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open);
int len = (int)fs.Length;
byte[] data = new byte[len];
fs.Read(data, 0, len);
fs.Close();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(data);
string fileMD5 = "";
foreach (byte b in result)
{
fileMD5 += Convert.ToString(b, 16);
}
return fileMD5;
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
return "";
}
}
調用的時候通過填寫制定文件的完整目錄,即可獲得對應文件的MD5碼:
string md5 = getFileHash("E:\\MyPro\\cubetest.unity3d");
遊戲檢查更新的具體步驟
- 通過請求服務器獲取到服務器的MD5碼配置文件
- 獲取本地的MD5碼配置文件
- .逐個比對每個文件的MD5碼
- 統計MD5碼不一致的文件列表
- 從服務器下載更新文件列表中包含的文件