Friday, July 29, 2011

Check integrity of two files

This method is used to check the integrity of two files using MD5 checksum. It accepts two string parameters. The source file location and the destination file location.

public bool PerformHashCheck(string sourcepath, string destinationpath)
        {
            bool result = false;
            FileStream sourcefile = new FileStream(sourcepath, FileMode.Open);
            FileStream destinationfile = new FileStream(destinationpath, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] sourceBytes = md5.ComputeHash(sourcefile);
            byte[] destinationBytes = md5.ComputeHash(destinationfile);
            sourcefile.Close();
            destinationfile.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < sourceBytes.Length; i++)
            {
                sb.Append(sourceBytes[i].ToString("x2"));
            }
            string sourceHash = sb.ToString();
            StringBuilder db = new StringBuilder();
            for (int i = 0; i < destinationBytes.Length; i++)
            {
                db.Append(destinationBytes[i].ToString("x2"));
            }
            string desntinationHash = db.ToString();
            if (sourceHash.Equals(desntinationHash))
            {
                result = true;
            }
            return result;
        }

No comments:

Post a Comment