MD5 Stream Extension

// December 6th, 2009 // Useful Code

        /// <summary>
        /// COMPUTE THE HASH VALUE OF THE FILE STREAM
        /// </summary>
        /// <param name="s">STREAM TO COMPUTE THE VALUE OF</param>
        /// <param name="closeStream">BOOLEAN TO DETERMINE IF THE STREAM SHOULD BE CLOSED UPON EXIT</param>
        /// <returns>RETURNS AN MD5 HASH OF THE FILE</returns>
        public static string ComputeMD5(this Stream s, bool closeStream)
        {
            try
            {
                //SEEK TO THE BEGINING OF THE STREAM
                s.Seek(0, SeekOrigin.Begin);

                //CREATE AN MD5 AND COMPUTE THE HASH VALUE
                return BitConverter.ToString(MD5.Create().ComputeHash(s)).Replace("-", "");
            }
            catch
            {
                //THROW AN ERROR BECAUSE WE WERE UNABLE TO SEEK IN THE FILE OR POSSIBLY READ
                throw new ArgumentException("Invalid stream, must be able to seek and read.");
            }
            finally
            {
                //IF WE ARE SUPPOSED TO CLOSE THE STREAM WHEN WE ARE DONE THEN DO SO
                if (closeStream)
                    s.Close();
            }

        }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt