/// <summary> ///file Check/// </summary> Public classFileCheck {/// <summary> ///calculate the MD5 value of a file/// </summary> /// <param name= "FileName" >the file name and path to calculate the MD5 value</param> /// <returns>MD5 value 16 binary string</returns> Public stringMd5file (stringfileName) { Try { returnHashfile (FileName,"MD5"); } Catch { return NULL; } } /// <summary> ///calculate the SHA1 value of a file/// </summary> /// <param name= "FileName" >the file name and path to calculate the SHA1 value</param> /// <returns>SHA1 value 16 binary string</returns> Public stringSha1file (stringfileName) { Try { returnHashfile (FileName,"SHA1"); } Catch { return NULL; } } /// <summary> ///computes the hash value of a file/// </summary> /// <param name= "FileName" >the file name and path to calculate the hash value</param> /// <param name= "Algname" >algorithm: Sha1,md5</param> /// <returns>hash Value 16 binary string</returns> Private stringHashfile (stringFileName,stringalgname) { if(!System.IO.File.Exists (fileName))return string. Empty; System.IO.FileStream FS=NewSystem.IO.FileStream (FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] Hashbytes =hashdata (FS, algname); Fs. Close (); returnbytearraytohexstring (hashbytes); } /// <summary> ///Calculate 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,stringalgname) {System.Security.Cryptography.HashAlgorithm algorithm; if(Algname = =NULL) { Throw NewArgumentNullException ("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 NewException ("Algname can only use SHA1 or MD5"); } algorithm=System.Security.Cryptography.MD5.Create (); } returnAlgorithm.computehash (stream); } /// <summary> ///byte array converted to a string of 16 binary representations/// </summary> Private stringBytearraytohexstring (byte[] buf) { returnBitconverter.tostring (BUF). Replace ("-",""); } }
C # Gets the value of the file MD5, SHA1