| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
- namespace Update.Utils
- {
- public static class FileExtensions
- {
- /// <summary>
- /// 生成文件的md5
- /// </summary>
- /// <param name="filename"></param>
- /// <returns></returns>
- private static string FilenameMutexKey(string filename)
- {
- return Functions.GenMd5(filename);
- }
- /// <summary>
- /// 写入二进制值
- /// </summary>
- /// <param name="filename"></param>
- /// <param name="bytes"></param>
- public static void WriteBytes(string filename, byte[] bytes)
- {
- if (bytes != null)
- {
- string key = FilenameMutexKey(filename);
- CheckDirectory(Path.GetDirectoryName(filename), true);
- void act()
- {
- File.WriteAllBytes(filename, bytes);
- }
- MutexExtensions.Exec(key, act);
- }
- }
- /// <summary>
- /// 添加所有文本
- /// </summary>
- /// <param name="filename"></param>
- /// <param name="txt"></param>
- /// <param name="encoding"></param>
- public static void AppendAllText(string filename, string txt, Encoding encoding = null)
- {
- encoding = encoding ?? Encoding.UTF8;
- string key = FilenameMutexKey(filename);
- CheckDirectory(Path.GetDirectoryName(filename), true);
- void act()
- {
- File.AppendAllText(filename, txt, encoding);
- }
- MutexExtensions.Exec(key, act);
- }
- /// <summary>
- /// 检查目录是否存在,如果不存在,将根据条件创建或不创建
- /// </summary>
- /// <param name="p"></param>
- /// <param name="create">如果目录不存在,是否创建</param>
- /// <returns></returns>
- public static bool CheckDirectory(string p, bool create)
- {
- bool res = false;
- if (!string.IsNullOrEmpty(p))
- {
- res = Directory.Exists(p);
- if (!res && create)
- {
- Directory.CreateDirectory(p);
- res = true;
- }
- }
- return res;
- }
- /// <summary>
- /// 获取制定路径文件的md5值
- /// </summary>
- /// <param name="filename"></param>
- /// <returns></returns>
- public static string FileMd5(string filename)
- {
- string res = "";
- try
- {
- using (FileStream file = new FileStream(filename, FileMode.Open))
- using (MD5 md5 = new MD5CryptoServiceProvider())
- {
- byte[] retVal = md5.ComputeHash(file);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("x2"));
- }
- res = sb.ToString();
- }
- }
- catch
- {
- }
- return res;
- }
- }
- }
|