I tidied up your code, look how it turned out:
using (var client = new HttpClient())
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(path));
using (var content = new MultipartFormDataContent("Upload"))
{
content.Add(fileContent);
var result = client.PostAsync("file/upload", content).Result;
using (var message = client.PostAsync("file/upload", content).Result)
{
var response = message.Content.ReadAsByteArrayAsync().Result;
Console.WriteLine("Status: " + result.StatusCode);
}
}
}
Some remarks:
is using async methods synchronously and expecting the
Result
, try to turn your method into async and use await
in
async operations (for example await client.PostAsync("file/upload",
content)
.
not seen in your code, but some objects are Disposable, that is, they can be using within a block of code using
, like the
HttpClient
, that will release the resources once the using block is closed. If you don’t know how it works, search right here on the site
has several questions and answers on the subject.