using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Update.Utils
{
public static class FileExtensions
{
///
/// 生成文件的md5
///
///
///
private static string FilenameMutexKey(string filename)
{
return Functions.GenMd5(filename);
}
///
/// 写入二进制值
///
///
///
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);
}
}
///
/// 添加所有文本
///
///
///
///
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);
}
///
/// 检查目录是否存在,如果不存在,将根据条件创建或不创建
///
///
/// 如果目录不存在,是否创建
///
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;
}
///
/// 获取制定路径文件的md5值
///
///
///
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;
}
}
}