c# 如何给文件计算MD5

在项目中,当我们需要把数据文件上传到ftp时,为了保证数据的完整性,我们会计算数据文件的MD5,并把MD5文件和数据文件一同上传。

那么如何产生数据文件的MD5呢?


我们可以通过System.Security.Cryptography.MD5类来

private void WriteMD5(string zipFile, string ctrlFile)
        {
            // Add hash code to ctrl file
            byte[] validHash = GenerateMD5Hash(zipFile);
            // make sure that we add hash value in a new line
            bool addNewLine = false;
            using (StreamReader sr = new StreamReader(ctrlFile))
            {
                string[] lines = sr.ReadToEnd().Split(new char[] { '\n' });
                if (lines.Length == 1) addNewLine = true;
            }

            // ready to put the control file, so add the hash string to it
            using (StreamWriter sw = new StreamWriter(ctrlFile, true))
            {
                if (addNewLine) sw.WriteLine("");
                sw.WriteLine(BitConverter.ToString(validHash).Replace("-", ""));
            }
        }


private byte[] GenerateMD5Hash(string localFileName)
        {
            byte[] localHash = null;
            using (MD5 md5Hash = MD5.Create())
            {
                using (FileStream localFile = File.OpenRead(localFileName))
                {
                    localHash = md5Hash.ComputeHash(localFile);
                }
            }
            return localHash;
        }