Home c# HttpClient.PostAsync only works once

# 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())
{
var response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
//code is stopping at the following line:
Console.WriteLine(finalresults);
Console.WriteLine(" > Uploaded file " + info.Name);
}
stream.Close();
}
}
}


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?

• 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