Home c# HttpClient.PostAsync only works once
Reply: 0

c# HttpClient.PostAsync only works once

user6938
1#
user6938 Published in September 19, 2018, 3:25 am

I'm working on a windows client for uploading a lot of small files over an http post request. I’m using .NET 4.5.2

public async void Upload3(HttpClient client, string url, string[] files)
{
    foreach (var file in files)
    {
        using (var stream = new FileStream(file, FileMode.Open))
        {
            FileInfo info = new FileInfo(file);
            HttpContent fileStreamContent = new StreamContent(stream);
            using (var content = new MultipartFormDataContent())
            {
                content.Add(fileStreamContent);
                var response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                //code is stopping at the following line:
                string finalresults = await response.Content.ReadAsStringAsync();
                Console.WriteLine(finalresults);
                Console.WriteLine(" > Uploaded file " + info.Name);
            }
            stream.Close();
        }
    }
    Console.WriteLine("> Uploaded all files");
}

The Code is working fine for the very first file. But every other file is not uploaded. When I try to debug the code step by step, the code execution stops (in the second iteration of the loop) on this line:

string finalresults = await response.Content.ReadAsStringAsync();

Since the server log only shows on single request, I think that the error already occurs in this line:

var response = await client.PostAsync(url, content);

Even if I use different HttpClient objects and different FileStream objects, the upload is only working for the first file. What is wrong with this code?

share|improve this question
  • How are you calling this function? Are you awaiting it properly all the way up the chain? – DavidG Jan 12 at 15:07
  • Yes. The problem is not that it is shutdown before it has finished. It just stops at "await response..." and after a few minutes it throws a generic exception. – Vlorian Jan 12 at 15:19

1 Answer 1

active oldest votes
up vote 0 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.369631 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO