在進行開發時,對文件進行上傳和下載是較為普遍的行為,為了防止在文件操作過程中,出現同一文件多次操作,需要對文件進行相同性比較:
1.獲取文件的絕對路徑,針對window程序和web程序都可使用:
/// <summary>
/// 獲取文件的絕對路徑,針對window程序和web程序都可使用
/// </summary>
/// <param name="relativePath">相對路徑地址</param>
/// <returns>絕對路徑地址</returns>
public static string GetAbsolutePath(string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
{
throw new ArgumentNullException("參數relativePath空異常!");
}
relativePath = relativePath.Replace("/", "\\");
if (relativePath[0] == '\\')
{
relativePath=relativePath.Remove(0, 1);
}
//判斷是Web程序還是window程序
if (HttpContext.Current != null)
{
return Path.Combine(HttpRuntime.AppDomainAppPath, relativePath);
}
else
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath);
}
}
2.獲取文件的絕對路徑,針對window程序和web程序都可使用:
/// <summary>
/// 獲取文件的絕對路徑,針對window程序和web程序都可使用
/// </summary>
/// <param name="relativePath">相對路徑地址</param>
/// <returns>絕對路徑地址</returns>
public static string GetRootPath()
{
//判斷是Web程序還是window程序
if (HttpContext.Current != null)
{
return HttpRuntime.AppDomainAppPath;
}
else
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
3.通過文件Hash 比較兩個文件內容是否相同:
/// <summary>
/// 通過文件Hash 比較兩個文件內容是否相同
/// </summary>
/// <param name="filePath1">文件1地址</param>
/// <param name="filePath2">文件2地址</param>
/// <returns></returns>
public static bool isValidFileContent(string filePath1, string filePath2)
{
//創建一個哈希算法對象
using (HashAlgorithm hash = HashAlgorithm.Create())
{
using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
{
byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根據文本得到哈希碼的字節數組
byte[] hashByte2 = hash.ComputeHash(file2);
string str1 = BitConverter.ToString(hashByte1);//將字節數組裝換為字符串
string str2 = BitConverter.ToString(hashByte2);
return (str1 == str2);//比較哈希碼
}
}
}
4.計算文件的hash值 用於比較兩個文件是否相同:
/// <summary>
/// 計算文件的hash值 用於比較兩個文件是否相同
/// </summary>
/// <param name="filePath">文件路徑</param>
/// <returns>文件hash值</returns>
public static string GetFileHash(string filePath)
{
//創建一個哈希算法對象
using (HashAlgorithm hash = HashAlgorithm.Create())
{
using (FileStream file = new FileStream(filePath, FileMode.Open))
{
//哈希算法根據文本得到哈希碼的字節數組
byte[] hashByte= hash.ComputeHash(file);
//將字節數組裝換為字符串
return BitConverter.ToString(hashByte);
}
}
}