温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c# 如何给文件计算MD5

发布时间:2020-07-31 07:26:49 来源:网络 阅读:616 作者:13713878410 栏目:编程语言

在项目中,当我们需要把数据文件上传到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;
        }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI