C# get md5,renamed file and can not change file's md5

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace ConsoleApplication13
{
    class Program
    {
        static void Main(string[] args)
        {
            string imgPath1 = @"..\..\Images\lj.jpg";
            string imgPath2 = @"..\..\Images\lj2.jpg";
            string imgPath3 = @"..\..\Images\lj3.jpg";
            string imgPath4 = @"..\..\Images\lj4.jpg";
            string md51 = GetMD5(imgPath1);
            string md52 = GetMD5(imgPath2);
            string md53 = GetMD5(imgPath3);
            string md54 = GetMD5(imgPath4);
            Console.WriteLine($"path:{imgPath1},md51:{md51}");
            Console.WriteLine($"path:{imgPath2},md52:{md52}");
            Console.WriteLine($"path:{imgPath3},md53:{md53}");
            Console.WriteLine($"path:{imgPath4},md54:{md54}");
            Console.ReadLine();
        }

        static string GetMD5(string sourceFile)
        {
            StringBuilder md5Builder = new StringBuilder();
            if (File.Exists(sourceFile))
            {
                using (MD5 md5Hash = MD5.Create())
                {
                    using(FileStream fs=File.Open(sourceFile,FileMode.Open))
                    {
                        byte[] md5Bytes = md5Hash.ComputeHash(fs);
                        for (int i = 0; i < md5Bytes.Length; i++)
                        {
                            string sortedByte = md5Bytes[i].ToString("x2");
                            if (!string.IsNullOrEmpty(sortedByte))
                            {
                                md5Builder.Append(sortedByte);
                            }
                        }
                    }                      
                }
            }
            return md5Builder.ToString();
        }
    }
}

 

posted @ 2019-12-09 11:18  FredGrit  阅读(284)  评论(0编辑  收藏  举报