Calculate MD5 checksum for a file

前端 未结 6 829
囚心锁ツ
囚心锁ツ 2020-11-22 08:03

I\'m using iTextSharp to read the text from a PDF file. However, there are times I cannot extract text, because the PDF file is only containing images. I download the same P

6条回答
  •  旧时难觅i
    2020-11-22 08:25

    It's very simple using System.Security.Cryptography.MD5:

    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            return md5.ComputeHash(stream);
        }
    }
    

    (I believe that actually the MD5 implementation used doesn't need to be disposed, but I'd probably still do so anyway.)

    How you compare the results afterwards is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don't override Equals. Using base64 is simpler to get right, but slightly less efficient if you're really only interested in comparing the hashes.)

    If you need to represent the hash as a string, you could convert it to hex using BitConverter:

    static string CalculateMD5(string filename)
    {
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(filename))
            {
                var hash = md5.ComputeHash(stream);
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }
    }
    

提交回复
热议问题