/// <Summary> /// Calculate the MD5 value of a file /// </Summary> /// <Param name = "FILENAME"> Name and path of the file to calculate the MD5 Value </Param> /// <Returns> MD5 value: A hexadecimal string </Returns> Public String Md5file ( String Filename) { Return Hashfile (filename, " MD5 " ); }
/// <Summary> /// Calculate the sha1 value of the file /// </Summary> /// <Param name = "FILENAME"> Name and path of the file to calculate the sha1 Value </Param> /// <Returns> Sha1 value hexadecimal string </Returns> Public String Sha1file ( String Filename) { Return Hashfile (filename, " Sha1 " ); }
/// <Summary> /// Calculate the file hash value /// </Summary> /// <Param name = "FILENAME"> Name and path of the file to calculate the hash value </Param> /// <Param name = "algname"> Algorithm: Sha1, MD5 </Param> /// <Returns> Hash Value: A hexadecimal string </Returns> Private String Hashfile ( String Filename, String Algname) { If ( ! System. Io. file. exists (filename )) Return String . Empty;
System. Io. filestream FS = New System. Io. filestream (filename, system. Io. filemode. Open, system. Io. fileaccess. Read ); Byte [] Hashbytes = Hashdata (FS, algname ); FS. Close (); Return Bytearraytohexstring (hashbytes ); }
/// <Summary> /// Calculate the hash value /// </Summary> /// <Param name = "stream"> Stream to calculate the hash value </Param> /// <Param name = "algname"> Algorithm: sha1, MD5 </Param> /// <Returns> Hash Value byte array </Returns> Private Byte [] Hashdata (system. Io. Stream stream, String Algname) { System. Security. cryptography. hashalgorithm algorithm; If (Algname = Null ) { Throw New Argumentnullexception ( " Algname cannot be null " ); } If ( String . Compare (algname, " Sha1 " , True ) = 0 ) { Algorithm = System. Security. cryptography. sha1.create (); } Else { If ( String . Compare (algname, " MD5 " , True ) ! = 0 ) { Throw New Exception ( " Algname can only use sha1 or MD5 " ); } Algorithm = System. Security. cryptography. md5.create (); } Return Algorithm. computehash (Stream ); }
/// <Summary> /// Byte array to a hexadecimal string /// </Summary> Private String Bytearraytohexstring ( Byte [] BUF) { Return Bitconverter. tostring (BUF). Replace ( " - " , "" ); } |