Unity热更新获取所有文件MD5值

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;

namespace myMD
{
class Program
{
/// <summary>
/// 获取本地某个文件夹下所有文件MD5
/// </summary>

static string resPath = @"G:\netboxServer\NetBox 2.8\server\www\AssetsBundle\gameobject";
public static void Main()
{
// 获取Res文件夹下所有文件的相对路径和MD5值
string[] files = Directory.GetFiles(resPath, "*", SearchOption.AllDirectories);//获取res路径下所有文件
StringBuilder versions = new StringBuilder(); //字符流,存储文件名+MD5
for (int i = 0, len = files.Length; i < len; i++) //遍历所有文件
{
string filePath = files[i];
string extension = filePath.Substring(files[i].LastIndexOf(".")); //截取最后一个 "." 后边的字符
if (extension == ".ab") // .ab为Unity打包出来的AssetBundle资源,自定义的后缀
{
string relativePath = filePath.Replace(resPath, "").Replace("\\", "/");//将完整路径中的文件前边去除,获取文件名
string md5 = MD5File(filePath); //获取MD5值
versions.Append(relativePath).Append(",").Append(md5).Append("\n");//写入字节流 (文件名,MD5值)换行
}
}
// 生成配置文件
FileStream stream = new FileStream(@"C: \Users\Administrator\Desktop\" + "version.txt", FileMode.Create);
byte[] data = Encoding.UTF8.GetBytes(versions.ToString());
stream.Write(data, 0, data.Length);
stream.Flush();
stream.Close();

}


//dier
public static string MD5File(string file)
{
try
{
FileStream fs = new FileStream(file, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();//创建对象
byte[] retVal = md5.ComputeHash(fs); // 获取md5值, 是一个Hash字节数组
fs.Close(); //关闭文件流
StringBuilder sb = new StringBuilder(); //使用字符流节省性能
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2")); //x2:以16进制转换
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("md5file() fail, error:" + ex.Message);
}
}
}
}

posted @ 2018-07-03 11:04  吃豆人  阅读(817)  评论(0编辑  收藏  举报