Uploading to Amazon S3 from C# with an Explicit Object Contract

Editorial illustration.

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

Calling PutObjectAsync in the AWS SDK for .NET takes about five lines of code. The trouble starts six months later when your bucket has 40,000 files named invoice.pdf and Screenshot 2023-06-16.png sitting in the root, half of them orphaned because a database write failed, and no one is sure which ones are supposed to be public.

Whether you are targeting Amazon S3 (say, ap-southeast-1 in Singapore for low latency from Malaysia) or an S3-compatible store like Cloudflare R2, the upload itself is the easy part. Designing the object key, credentials, and access model is what keeps the bucket maintainable.

Never let the browser choose the S3 key

A classic shortcut in early prototypes is using file.FileName directly as the S3 Key. That invites three immediate problems:

  • Two users uploading receipt.pdf silently overwrite each other.
  • Spaces, unicode characters, or ../ segments in filenames create awkward URLs and path-handling bugs.
  • You have no clean way to delete or audit all files belonging to a specific tenant or record.

Instead, let the application generate a deterministic or UUID-based key, and store the user’s original filename in your database (or in S3’s Metadata / ContentDisposition if needed):

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;

public sealed class DocumentStorageService
{
    private readonly IAmazonS3 _s3;
    private readonly string _bucketName;

    public DocumentStorageService(IAmazonS3 s3, string bucketName)
    {
        _s3 = s3;
        _bucketName = bucketName;
    }

    public async Task<string> UploadAsync(
        Guid tenantId,
        Stream content,
        string contentType,
        string extension,
        CancellationToken cancellationToken)
    {
        string safeExt = extension.TrimStart('.').ToLowerInvariant();
        string objectKey = $"tenants/{tenantId:N}/{DateTime.UtcNow:yyyy/MM}/{Guid.NewGuid():N}.{safeExt}";

        var request = new PutObjectRequest
        {
            BucketName = _bucketName,
            Key = objectKey,
            InputStream = content,
            ContentType = contentType,
            AutoCloseStream = false,
            ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
        };

        await _s3.PutObjectAsync(request, cancellationToken);
        return objectKey;
    }
}

Notice AutoCloseStream = false. By default, the AWS SDK closes InputStream after the upload completes. If your caller still needs to compute a SHA-256 hash or inspect the stream, or owns it in an outer using block, leaving AutoCloseStream on the default true can cause unexpected disposal errors.

Keep credentials out of code and keep the bucket private

Do not pass new AmazonS3Client("AKIA...", "secret...") in C#. In production on EC2, ECS, or Lambda, attach an IAM role with s3:PutObject and s3:GetObject scoped to that specific bucket (arn:aws:s3:::my-app-docs/*). Locally, use aws configure profiles or environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION), and register IAmazonS3 via AWSSDK.Extensions.NETCore.Setup:

builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonS3>();

Just as important: leave Block All Public Access turned on at the bucket level. If a user needs to download an invoice or attachment, have your API verify their session and permissions first, then issue a short-lived presigned URL (GetPreSignedURLAsync with a 5–15 minute expiry) or serve public marketing assets through CloudFront with Origin Access Control. Never flip CannedACL = S3CannedACL.PublicRead just to make a download link work quickly.

Handle the split between S3 and your database

S3 and SQL Server do not share a two-phase commit. If you write the database row first and S3 fails, you have a broken link in the UI; if you upload to S3 first and the database transaction rolls back, you have an orphaned object costing storage forever.

The cleanest pattern for most business apps is:

  1. Upload to S3 first and get the objectKey back.
  2. Wrap your SQL INSERT in a try/catch. If the database write fails, make a best-effort DeleteObjectAsync call in the catch block so failed requests don’t leak objects.
  3. For large files (over ~100 MB) or mobile clients on flaky connections, skip proxying bytes through your ASP.NET server altogether—generate a presigned PUT URL instead so the client uploads straight to S3, then confirm the key in your API once the upload finishes.