How do I create an MD5 hash digest from a text file?

后端 未结 4 1129
终归单人心
终归单人心 2020-12-05 18:12

Using C#, I want to create an MD5 hash of a text file. How can I accomplish this?

Update: Thanks to everyone for their help. I\'ve finally settled u

4条回答
  •  春和景丽
    2020-12-05 18:59

    Here is a .NET Standard version that doesn't require reading the entire file into memory:

        private byte[] CalculateMD5OfFile(FileInfo targetFile)
        {
            byte[] hashBytes = null;
            using (var hashcalc = System.Security.Cryptography.MD5.Create())
            {
                using (FileStream inf = targetFile.OpenRead())
                    hashcalc.ComputeHash(inf);
                hashBytes = hashcalc.Hash;
            }
            return hashBytes;
        }
    

    You can convert the byte[] array into a string using the methods shown above. Also: You can change "MD5" in the third line to SHA1, SHA256, etc. to calculate other hashes.

提交回复
热议问题