0

I have the following Method that gets the posted files.

What is the best approach to calculate the MD5 hash and where ?

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                string fileName = context.Server.MapPath("~/uploads/" + file.FileName);
                file.SaveAs(fileName);
                int Size = file.ContentLength;
            }

        }
    }
Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • 2
    Possible duplicate of [Calculate MD5 checksum for a file](https://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file) – jAC Sep 13 '17 at 08:30
  • Possible duplicate of [How can I generate an MD5 hash?](https://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash) – Mohmmad S Oct 23 '18 at 01:55

1 Answers1

0

When you "upload" a file, it is just stored in memory on the server until you do something with it (and if you do nothing, it's lost at the end of the request handler). Since you also need to read it into memory to compute the md5, you can skip the step of writing to disk, at least for the MD5 part:

public void ProcessRequest(HttpContext context)
{
    using (var md5 = MD5.Create())
    {
        foreach (var file in context.Request.Files)
        {
            var hash = md5.ComputeHash(file.InputStream);

            // do whatever with the file + md5 now
        }
    }
}

You can still write it to disk after this if that's what you want, but doing the md5 calculation first saves reading it back out again, plus lets you do duplicate checking or lets you name the file based on the hash.

You should also strongly consider a better hash than md5, as it's considered weak these days. SHA256 is a popular and solid choice.

gregmac
  • 24,276
  • 10
  • 87
  • 118
  • This question is an old of mine, i changed paths and TBH i just edited to make a better question format, however thank you for suggesting SHA256 i would love to read about such thing – Mohmmad S Oct 23 '18 at 03:59