RuralPowerCompetition_yizhe.../RuralPowerCompetition_yizheng1/Assets/FileValdate.cs

54 lines
1.8 KiB
C#

using System;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace FileChecker
{
internal class FileValdate
{
public static bool Valdate(string rootPath, string resPath)
{
try
{
string path = rootPath + "\\" + resPath;
string text = System.IO.File.ReadAllText(path);
byte[] data = Convert.FromBase64String(text);
byte[] buffer = new byte[data.Length - 4];
Array.Copy(data, 2, buffer, 0, data.Length - 4);
text = Encoding.UTF8.GetString(buffer);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(text);
XmlElement root = (XmlElement)xmlDoc.ChildNodes[0];
var fileNodes = root.ChildNodes;
foreach (XmlNode node in fileNodes)
{
XmlElement fileNode = (XmlElement)node;
string filePath = rootPath + "\\" + fileNode.GetAttribute("path");
string fileCode = fileNode.GetAttribute("code");
string realCode = GetFileHash(filePath);
if (!fileCode.Equals(realCode))
return false;
}
return true;
}
catch { return false; }
}
public static string GetFileHash(string filePath)
{
string hash = "ABCD123";
using (var md5 = MD5.Create())
{
using (var stream = System.IO.File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
return hash;
}
}
}