Using system; namespace mymethod {class computemd5andsha1 {// <summary> // calculate the MD5 value of the file /// </Summary> /// <Param name = "FILENAME"> to calculate MD5 value File Name and path </param> // <returns> MD5 value 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's 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 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> // convert the byte array to a hex string // </Summary> private string bytearraytohexstring (byte [] BUF) {return bitconverter. tostring (BUF ). replace ("-","");}}}