Skip to content
Console

Connect to S4 with .NET

Uses the AWS SDK for .NET 4.x. The code below can be placed in a single Program.cs and run in order.

Prerequisites

  1. Create a bucket in the console;
  2. Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
  3. Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"

Install

dotnet add package AWSSDK.S3

The examples on this page were tested on .NET 9 and AWSSDK.S3 4.1.2.

Connect to S4

Program.cs
using System.Net;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;

var s3 = new AmazonS3Client(
    new BasicAWSCredentials(
        Environment.GetEnvironmentVariable("S4_ACCESS_KEY"),
        Environment.GetEnvironmentVariable("S4_SECRET_KEY")),
    new AmazonS3Config
    {
        ServiceURL = "https://s3.bitiful.net",
        AuthenticationRegion = "cn-east-1",
    });

var bucket = "my-bucket";

AuthenticationRegion must be set, otherwise the signature uses the wrong region. AmazonS3Client is thread-safe; create one per process.

Upload files

An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.

Program.cs
// Upload a text string
await s3.PutObjectAsync(new PutObjectRequest
{
    BucketName = bucket,
    Key = "docs/hello.txt",
    ContentBody = "你好,S4",
    ContentType = "text/plain; charset=utf-8",
});

// Upload a local file, setting cache time and custom metadata
var put = new PutObjectRequest
{
    BucketName = bucket,
    Key = "images/photo.jpg",
    FilePath = "photo.jpg",
    ContentType = "image/jpeg",
};
put.Headers.CacheControl = "max-age=86400";
put.Metadata.Add("author", "bitiful");
await s3.PutObjectAsync(put);

Upload large files

Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.

Program.cs
using var transfer = new TransferUtility(s3, new TransferUtilityConfig
{
    MinSizeBeforePartUpload = 16 * 1024 * 1024, // Split automatically above 16 MiB
    ConcurrentServiceRequests = 4,              // 4 parts uploaded at a time
});
var upload = new TransferUtilityUploadRequest
{
    BucketName = bucket,
    Key = "videos/video.mp4",
    FilePath = "video.mp4",
    ContentType = "video/mp4",
    PartSize = 16 * 1024 * 1024, // 16 MiB per part
};
upload.UploadProgressEvent += (_, e) => Console.WriteLine($"{e.PercentDone}%");
await transfer.UploadAsync(upload);

Download files

Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.

Program.cs
// Read as a string
using (var res = await s3.GetObjectAsync(bucket, "docs/hello.txt"))
using (var reader = new StreamReader(res.ResponseStream))
{
    Console.WriteLine(await reader.ReadToEndAsync());
}

// Save to a file
await transfer.DownloadAsync("video-copy.mp4", bucket, "videos/video.mp4");

// Read only the first 1 KiB
using var part = await s3.GetObjectAsync(new GetObjectRequest
{
    BucketName = bucket,
    Key = "videos/video.mp4",
    ByteRange = new ByteRange(0, 1023),
});
Console.WriteLine(part.ContentRange);

List files

Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.

Program.cs
// List all objects under a prefix, paging automatically
var pages = s3.Paginators.ListObjectsV2(new ListObjectsV2Request
{
    BucketName = bucket,
    Prefix = "images/",
});
await foreach (var obj in pages.S3Objects)
{
    Console.WriteLine($"{obj.Key} {obj.Size} {obj.LastModified}");
}

// List only the top-level directories
var root = await s3.ListObjectsV2Async(new ListObjectsV2Request
{
    BucketName = bucket,
    Delimiter = "/",
});
foreach (var p in root.CommonPrefixes ?? [])
{
    Console.WriteLine($"Directory {p}");
}

Get file information

Retrieve metadata without downloading the content. You can also use this to check whether an object exists.

Program.cs
async Task<bool> ExistsAsync(string key)
{
    try
    {
        await s3.GetObjectMetadataAsync(bucket, key);
        return true;
    }
    catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.NotFound)
    {
        return false;
    }
}

Console.WriteLine(await ExistsAsync("images/none.jpg"));

Copy and move

Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.

Program.cs
await s3.CopyObjectAsync(bucket, "images/photo.jpg", bucket, "images/photo-copy.jpg");

Move (?move=true) requires rewriting the CopySource request header, and the .NET SDK has no direct parameter for it. Move objects in the console or call it from another language. See Move and rename objects.

Delete files

Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.

Program.cs
// Delete one object
await s3.DeleteObjectAsync(bucket, "docs/hello.txt");

// Batch delete, up to 1000 objects at a time
var keys = new[] { "images/a.jpg", "images/b.jpg" };
try
{
    await s3.DeleteObjectsAsync(new DeleteObjectsRequest
    {
        BucketName = bucket,
        Objects = keys.Select(k => new KeyVersion { Key = k }).ToList(),
        Quiet = true,
    });
}
catch (DeleteObjectsException e)
{
    foreach (var err in e.Response.DeleteErrors)
    {
        Console.WriteLine($"{err.Key} {err.Code} {err.Message}");
    }
}

Presigned URLs

A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.

Program.cs
// Download URL, valid for 1 hour, with a specified file name
var get = new GetPreSignedUrlRequest
{
    BucketName = bucket,
    Key = "images/photo.jpg",
    Verb = HttpVerb.GET,
    Expires = DateTime.UtcNow.AddHours(1),
};
get.ResponseHeaderOverrides.ContentDisposition = "attachment; filename=\"photo.jpg\"";
var getUrl = await s3.GetPreSignedURLAsync(get);
Console.WriteLine(getUrl);

// Upload URL, valid for 10 minutes; the client sends a PUT to it
var putUrl = await s3.GetPreSignedURLAsync(new GetPreSignedUrlRequest
{
    BucketName = bucket,
    Key = "uploads/avatar.jpg",
    Verb = HttpVerb.PUT,
    Expires = DateTime.UtcNow.AddMinutes(10),
});
Console.WriteLine(putUrl);

Presigned URLs with extension parameters

Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.

Program.cs
var extra = new GetPreSignedUrlRequest
{
    BucketName = bucket,
    Key = "images/photo.jpg",
    Verb = HttpVerb.GET,
    Expires = DateTime.UtcNow.AddHours(1),
};
// Only parameters starting with x- can be added; they are included in the signature
extra.Parameters.Add("x-bitiful-limit-rate", "1048576"); // Per-connection rate limit of 1 MiB/s
extra.Parameters.Add("x-bitiful-max-requests", "3");     // At most 3 accesses
Console.WriteLine(await s3.GetPreSignedURLAsync(extra));

The .NET SDK forces an x- prefix on custom parameter names, so you can only use x-bitiful-* and x-amz-* parameters here; you cannot add CoreIX parameters such as w and fmt directly. For image processing, first create a Style in the console, then sign the key as images/photo.jpg!style:style-name.

Conditional writes

Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.

Program.cs
try
{
    // Write only if the object does not exist, to prevent overwriting
    await s3.PutObjectAsync(new PutObjectRequest
    {
        BucketName = bucket,
        Key = "locks/job",
        ContentBody = "me",
        IfNoneMatch = "*",
    });
}
catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.PreconditionFailed)
{
    Console.WriteLine("Object already exists");
}

Handle errors

For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.

Program.cs
try
{
    await s3.GetObjectAsync(bucket, "not-exists.txt");
}
catch (AmazonS3Exception e) when (e.ErrorCode == "NoSuchKey")
{
    Console.WriteLine("Object does not exist");
}
catch (AmazonS3Exception e)
{
    Console.WriteLine($"{(int)e.StatusCode} {e.ErrorCode} {e.Message} {e.RequestId}");
}
catch (AmazonClientException e)
{
    Console.WriteLine($"Network error: {e.Message}");
}

FAQ

Returns 403 AccessDenied

The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.

Returns SignatureDoesNotMatch

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.

Download speed is low

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.