Five Ways to Upload a File from C# to a Web Service

Editorial illustration.

Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.

The requirement sounds simple enough: take a file in C# and send it to another web service. Most developers start by searching for a quick HttpClient snippet, paste it in, see a 200 OK on a 50 KB test PDF, and move on. Then production hits—someone uploads a 150 MB video, a flaky mobile connection drops at 80%, or the receiving API expects raw binary instead of form data.

The right C# code depends entirely on the receiving endpoint’s contract and how failures need to be handled. Choosing the transport pattern first saves a lot of rewriting later.

Matching the Upload Pattern to the API

Before writing any HttpClient code, check what the receiving service actually expects:

Approach When it fits
Multipart HTTP upload (multipart/form-data) Form-style APIs accepting a file alongside metadata fields
Raw binary request body (PUT/POST) Endpoints expecting only the file bytes and a Content-Type header
Presigned object-storage upload Backends that issue short-lived URLs for S3, Cloudflare R2, or Azure Blob
Chunked or resumable protocol Large files over unreliable links where restarting from zero is painful
Vendor SDK Services with a maintained .NET client that handles auth, retries, and signing

These five patterns are not interchangeable. Sending multipart/form-data to an endpoint expecting raw binary will leave multipart boundary headers inside the saved file on the other side.

Streaming Multipart Form Data Without Blowing Up Memory

When integrating with traditional REST APIs or ASP.NET MVC/Web API controllers, MultipartFormDataContent is the standard choice. The biggest mistake in older C# snippets is calling File.ReadAllBytes(filePath) and wrapping it in ByteArrayContent. For a 10 MB file on a busy server, that immediately allocates large arrays on the Large Object Heap.

Instead, stream the file directly from disk using StreamContent and let IHttpClientFactory manage the HttpClient lifecycle so you do not exhaust sockets under load:

await using var fileStream = File.OpenRead(filePath);
using var form = new MultipartFormDataContent();
using var streamContent = new StreamContent(fileStream);

streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
form.Add(streamContent, "file", Path.GetFileName(filePath));
form.Add(new StringContent(documentCategory), "category");

using var response = await httpClient.PostAsync(uploadUri, form, cancellationToken);
response.EnsureSuccessStatusCode();

Notice two small details that trip people up in real projects. First, pass a clean filename (Path.GetFileName), never a raw local path that leaks server directory structure. Second, set streamContent.Headers.ContentType explicitly; some strict API gateways reject uploads that default to application/octet-stream when they expect image/jpeg or application/pdf.

Raw Binary Bodies and Presigned Object Storage

If you are pushing files directly to Cloudflare R2, Amazon S3, or an internal microservice that accepts a raw stream, skip MultipartFormDataContent altogether. Send the StreamContent directly in a PUT or POST request:

await using var fileStream = File.OpenRead(filePath);
using var content = new StreamContent(fileStream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

using var request = new HttpRequestMessage(HttpMethod.Put, presignedUrl)
{
    Content = content
};

using var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();

Watch out for a common bug with presigned URLs: if you reuse a typed HttpClient that already has a default Authorization: Bearer ... header attached for your own backend API, sending that header to S3 or R2 will trigger a 400 Bad Request or signature mismatch error. Use a clean, unauthenticated HttpClient instance from IHttpClientFactory for presigned storage requests.

Chunked Uploads, Vendor SDKs, and Server Limits

Once files regularly cross 50–100 MB, single-request uploads become fragile. A brief network hiccup forces the whole transfer to restart. In those cases, look for a resumable protocol (such as tus, S3 multipart uploads, or Microsoft Graph upload sessions) or use the provider’s official .NET SDK, which already implements chunking, checksums, and exponential backoff.

Also remember that your own ASP.NET Core or IIS host has limits too. If your C# service acts as an intermediary receiving files before forwarding them, Kestrel defaults to roughly 28.6 MB (MaxRequestBodySize), and IIS has its own maxAllowedContentLength in web.config. Test with realistic file sizes early rather than discovering a 413 Payload Too Large in staging.

Retries, Idempotency, and Server-Side Validation

A 200 OK or 202 Accepted only tells you what the provider’s contract defines. Sometimes it means the file is stored; other times it means the file was queued for virus scanning and asynchronous processing.

Be careful with blind HTTP retries. If the server actually received the whole file and timed out right before sending the response, retrying a POST can create duplicate records unless the endpoint supports an idempotency key or upload session ID. When retrying with StreamContent, remember that a stream cannot be re-read unless CanSeek is true and you reset fileStream.Position = 0 between attempts—otherwise the retry sends zero bytes.

Finally, if you control the receiving web service as well, never trust the client’s filename, extension, or Content-Type header. Enforce size limits, verify file signatures on the server, and require proper authorization on the upload endpoint before accepting a single byte.