# Connect to S4 with .NET

> Connect to Bitiful S4 with the AWS SDK for .NET: C# examples for uploads, multipart uploads, downloads, listing, presigned URLs, extension parameters, and error handling.

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](https://docs.bitiful.com/en/bitiful-s4/handbook/buckets.md) in the console;
2. [Create a sub-user and AccessKey](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), and [grant the sub-user access to this bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). A new sub-user has no permissions;
3. Put the keys in environment variables instead of writing them in code:

```bash
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"
```

## Install

```bash
dotnet add package AWSSDK.S3
```

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

## Connect to S4

```csharp title="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](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md).

```csharp title="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.

```csharp title="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.

```csharp title="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 `/`.

```csharp title="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.

```csharp title="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](https://docs.bitiful.com/en/bitiful-s4/features/move-object.md).

```csharp title="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](https://docs.bitiful.com/en/bitiful-s4/features/move-object.md).

## 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.

```csharp title="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.

```csharp title="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](https://docs.bitiful.com/en/coreix/basic.md), rate limits, and request limits must be added **before signing**. Appending them after signing returns `SignatureDoesNotMatch`.

```csharp title="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));
```

> **Note**
>
> 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](https://docs.bitiful.com/en/coreix/handbook/styles.md) 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](https://docs.bitiful.com/en/developer/s3/conditional-requests.md).

```csharp title="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](https://docs.bitiful.com/en/developer/s3/errors.md). Rate limiting returns 429 `TooManyRequest`; catch it and retry with backoff.

```csharp title="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

<details>
<summary>Returns 403 AccessDenied</summary>

The sub-user has no permission on this bucket or directory. See [Sub-user permissions](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). Creating and deleting buckets can only be done in the console.

</details>

<details>
<summary>Returns SignatureDoesNotMatch</summary>

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the [checklist](https://docs.bitiful.com/en/developer/s3/errors.md).

</details>

<details>
<summary>Download speed is low</summary>

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a [CDN](https://docs.bitiful.com/en/cdn/intro.md) to serve visitors.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
