Sending a File using HttpClient in CSharp

C# - How to send a file with HttpClient | MAKOLYTE

Sending a Byte Array

If you already have a byte array, and don’t need to load the file as a file stream, then you can use ByteArrayContent instead of StreamContent. Here’s an example:

using (var multipartFormContent = new MultipartFormDataContent()) { 	
    //Add the file as a byte array 	
    var byteContent = new ByteArrayContent(fileBytesFromDatabase); 	
    byteContent.Headers.ContentType = new MediaTypeHeaderValue("image/png"); 	
    multipartFormContent.Add(byteContent, name: "file", fileName: "house.png"); 	
    //Send it 	
    var response = await httpClient.PostAsync("https://localhost:12345/files/", multipartFormContent); 	
    response.EnsureSuccessStatusCode(); 	
    return await response.Content.ReadAsStringAsync(); 
}

📇 Additional Metadata

  • 🗂 Type:: note
  • 🏷️ Tags:: CSharp
  • 📡 Status:: #status/🌲