/// <summary> /// 计算指定文件的MD5值 /// </summary> /// <param name="file">文件名</param> /// <returns>文件的MD5值(若出现异常则返回null)</returns> private byte[] _Get_File_MD5(string file) { byte[] ret = null; var csp = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] buffer = new byte[STREAM_BUFFER_SIZE]; csp.Initialize(); FileInfo fi = new FileInfo(file); FileStream fs = null; try { fs = fi.OpenRead(); } catch (Exception) { return ret; } //构造MD5计算事件的参数 File_MD5_Calculate_Event_Arg e = new File_MD5_Calculate_Event_Arg(); e.Current_Position = 0; e.File_Extension = fi.Extension; e.Full_File_Name = fi.FullName; e.File_Length = fi.Length; e.File_Name = fi.Name; if (File_MD5_Begin_Calculate_Event != null) File_MD5_Begin_Calculate_Event(e); //读取文件计算MD5 try { fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); int nRead = 0; do { nRead = fs.Read(buffer, 0, STREAM_BUFFER_SIZE); csp.TransformBlock(buffer, 0, nRead, buffer, 0); e.Current_Position += nRead; if (File_MD5_Calculating_Event != null) File_MD5_Calculating_Event(e); } while (nRead != 0); csp.TransformFinalBlock(buffer, 0, 0); ret = csp.Hash; } finally { try { fs.Close(); } catch (Exception) { } csp.Clear(); } if (File_MD5_End_Calculate_Event != null) File_MD5_End_Calculate_Event(e); return ret; }
/// <summary> /// 计算指定文件的MD5值 /// </summary> /// <param name="file">文件名</param> /// <returns>文件的MD5值(若出现异常则返回null)</returns> private byte[] _Get_File_MD5(string file) { byte[] ret = null; var csp = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] buffer = new byte[STREAM_BUFFER_SIZE]; csp.Initialize(); FileInfo fi = new FileInfo(file); FileStream fs = null; try { fs = fi.OpenRead(); } catch (Exception) { return(ret); } //构造MD5计算事件的参数 File_MD5_Calculate_Event_Arg e = new File_MD5_Calculate_Event_Arg(); e.Current_Position = 0; e.File_Extension = fi.Extension; e.Full_File_Name = fi.FullName; e.File_Length = fi.Length; e.File_Name = fi.Name; if (File_MD5_Begin_Calculate_Event != null) { File_MD5_Begin_Calculate_Event(e); } //读取文件计算MD5 try { fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); int nRead = 0; do { nRead = fs.Read(buffer, 0, STREAM_BUFFER_SIZE); csp.TransformBlock(buffer, 0, nRead, buffer, 0); e.Current_Position += nRead; if (File_MD5_Calculating_Event != null) { File_MD5_Calculating_Event(e); } } while (nRead != 0); csp.TransformFinalBlock(buffer, 0, 0); ret = csp.Hash; } finally { try { fs.Close(); } catch (Exception) { } csp.Clear(); } if (File_MD5_End_Calculate_Event != null) { File_MD5_End_Calculate_Event(e); } return(ret); }