1

I wanted to make an HTTP POST request with a big file so I composed C# code on .net core like following:

using (var fileStream = new FileStream(filePath, FileMode.Open))
using (var streamContent = new StreamContent(fileStream))
{
    var content = new MultipartFormDataContent();
    content.Add(streamContent);
    resp = await httpClient.PostAsync(requestUri, content);
}

It worked well for me. But, I found that it might be happy if SHA1 can be calculated during this context then it can be used for a simple caching for the POST result.

I found some answers on SO like the following:

How do I do a SHA1 File Checksum in C#?

But, I have no idea how I can use this to my code.

Here is what I tried so far:

byte[] hash = null;

using (SHA1Managed shaForStream = new SHA1Managed())
using (var fs = new FileStream(filePath, FileMode.Open))
using (var streamContent = new StreamContent(fs))
{
    var content = new MultipartFormDataContent();
    content.Add(streamContent);
    resp = await httpClient.PostAsync(requestUri, content);
    hash = shaForStream.ComputeHash(fs);
}

It is not working. For example, the sha1 value is the same for different files.

I think I might need to study Stream more. Could you tell me which materials do I need to study for this problem?

p.s, There are a couple of ways to cache request and response i.e., request params and response, but I want to do it with a SHA1 way for testing. I am just curious how I can do calculate something and request POST with only one stream. I can do it by creating two file streams. :)

sangheestyle
  • 1,037
  • 2
  • 16
  • 28
  • 1
    For what purpose are you trying to calculate the SHA1 hash? And why are you representing it as a string? What do you mean when you say 'it's definitely not working'? What is the expected behavior? – Hintham Oct 30 '18 at 16:31
  • @Hintham Hi! SHA1 is going to be used for a key for caching. So, sha1 and response of the request can be used a key-value pair. It doesn't need to be representing a string. Just need sha1. The current result of this code returns the same SHA1 value for any different kind of files. I want to get a correct one. FYI, there are a couple of ways to cache request and response i.e., request params and response, but I want to do with a SHA1 way for testing. This is not related to practicality. Is it enough for you? – sangheestyle Oct 30 '18 at 16:41
  • @Hintham I modified the code above. Thanks. – sangheestyle Oct 30 '18 at 16:44

0 Answers0