Sharon Watinsan
Sharon Watinsan

Reputation: 9850

How can I calculate the checksum of a IFormFile object

I have a file object in the form of IFormFile. I need to calculate the checksum of this file. How can I do this.

public string FindChecksum (IFormFile file){

  // How to calculate the checkSum

  return "THE CHECKSUM";
}

Upvotes: 2

Views: 1818

Answers (2)

kevin
kevin

Reputation: 1083

Another option, just in case someone finds it helpful:

public string CreatePackage(string packageType, IFormFile package)
{
    var hash = "";
    using (var md5 = MD5.Create())
    {
        using (var streamReader = new StreamReader(package.OpenReadStream()))
        {
              hash = BitConverter.ToString(md5.ComputeHash(streamReader.BaseStream)).Replace("-", "");
        }
    } 
    return hash;   
}

Upvotes: 0

dotnetstep
dotnetstep

Reputation: 17485

I would do something like this.

I assumed that you get data in IFromFile file argument.

public IActionResult IndexPost(IFormFile file)
        {
            Stream st =  file.OpenReadStream();
            MemoryStream mst = new MemoryStream();
            st.CopyTo(mst);            
            return Content(ToMD5Hash(mst.ToArray()));
        }       

        public static string ToMD5Hash(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                return null;

            using (var md5 = MD5.Create())
            {
                return string.Join("", md5.ComputeHash(bytes).Select(x => x.ToString("X2")));
            }
        }

Upvotes: 5

Related Questions