Scsl.S3
8.0.13
Prefix Reserved
See the version list below for details.
dotnet add package Scsl.S3 --version 8.0.13
NuGet\Install-Package Scsl.S3 -Version 8.0.13
<PackageReference Include="Scsl.S3" Version="8.0.13" />
paket add Scsl.S3 --version 8.0.13
#r "nuget: Scsl.S3, 8.0.13"
// Install Scsl.S3 as a Cake Addin #addin nuget:?package=Scsl.S3&version=8.0.13 // Install Scsl.S3 as a Cake Tool #tool nuget:?package=Scsl.S3&version=8.0.13
Using the R2Client Class for Cloudflare's S3-Compatible Storage
This guide explains how to use the R2Client
class to interact with an S3-compatible storage system. It includes instructions for configuring your application with dependency injection (DI), adding dynamic S3-based configuration, and using methods for uploading and deleting objects.
Perquisites
Install Scsl.S3 SDK for .NET You should install Scsl.S3 with NuGet:
Install-Package Scsl.S#
Or via .NET Core command line interface:
dotnet add package Scsl.S3
Either commands, from Package Manager Console or .NET Core CLI, will download and install Scsl.S3 and all required dependencies.
Configure
R2Options
Options in appsettings.json Ensure your application includes anR2Options
section. Example:{ "R2Options": { "PublicEndpoint": "https://example-public-endpoint", "BucketName": "string", "AccessKeyId": "string", "SecretAccessKey": "string", "Endpoint": "https://<ACCOUNT_ID>.r2.cloudflarestorage.com/" } }
Register Options in Dependency Injection (DI) Container:
Configure R2Options
in the DI container so it can be injected in the the R2Client
constructor.
Register the configuration in your Startup.cs
or Program.cs
:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<R2Options>(builder.Configuration.GetSection(R2Options.Name));
builder.Services.AddScoped<IR2Client, R2Client>();
S3-Based Configuration
Use the AddS3Configuration
extension method to dynamically load configuration files based on the environment and file structure. See here for usage.
Extension Method: AddS3Configuration
Method Signature
public static IConfigurationBuilder AddS3Configuration(
this IConfigurationBuilder builder,
string env,
string filePrefixName,
string subFolder = ""
)
Parameters
env
: The current environment (e.g.Development
,Production
).filePrefixName
: The prefix of the configuration file (e.g.appsettings
).subFolder
: (Optional) Subfolder where configuration files are stored.
Behavior
- Loads
appsettings.json
andappsettings.{env}.json
from the specifiedsubFolder
. - Defaults to the base path if no
subFolder is provided.
Example Setup in Programs.cs
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddS3Configuration(
env: builder.Environment.EnvironmentName,
filePrefixName: "appsettings",
subFolder: "config"
);
builder.Services.Configure<R2Options>(builder.Configuration.GetSection(R2Options.Name));
This configuration approach dynamically adapts to different environments.
Initialing the R2Client
The R2Client
constructor resolves IOptions<R2Options>
automatically from DI. Once configured, it’s ready for use in your application.
Example Initialization in a Controller
public class S3Controller
{
private readonly R2Client _r2Client;
public S3Controller(R2Client r2Client)
{
_r2Client = r2Client;
}
}
Uploading Files to S3-Compatible Storage
The R2Client
provides two methods for uploading files:
Method 1: PutObjectAsync
(Local File Path)
Uploads a file to the specified bucket using its local file path.
Method Signature
public async Task<S3ClientResult> PutObjectAsync(
string localFilePath,
string bucketName,
string key
)
Parameters
localFilePath
: Fill path to the local file.bucketName
: Name of the target bucket.key
: Object key (filename or folder/filename) in the bucket.
Example Usage
var localFilePath = @"C:\path\to\file.txt";
var bucketName = "example-bucket";
var key = "folder/file.txt";
var result = await _r2Client.PutObjectAsync(localFilePath, bucketName, key);
if (result == S3ClientResult.Success)
{
Console.WriteLine("File uploaded successfully.");
}
else
{
Console.WriteLine("File upload failed.");
}
Method 2: PutObjectAsync
(Stream)
Upload a file to the specified bucket using a Stream
.
Method Signature
public async Task<S3ClientResult> PutObjectAsync(Stream fileStream, string bucketName, string key)
Parameters
fileStream
: AStream
containing the file data.bucketName
: Name of the target bucket.key
: Object key (filename or folder/filename) in the bucket.
Example Usage
using var fileStream = File.OpenRead(@"C:\path\to\file.txt");
var bucketName = "example-bucket";
var key = "folder/file.txt";
var result = await _r2Client.PutObjectAsync(fileStream, bucketName, key);
if (result == S3ClientResult.Success)
{
Console.WriteLine("Stream uploaded successfully.");
}
else
{
Console.WriteLine("Stream upload failed.");
}
Deleting Files from S3-Compatible Storage
Method: DeleteObjectAsync
Removes an object from the specified bucket.
Method Signature
public async Task<S3ClientResult> DeleteObjectAsync(string bucketName, string key)
Example Usage
var bucketName = "example-bucket";
var key = "folder/file.txt";
var result = await _r2Client.DeleteObjectAsync(bucketName, key);
if (result == S3ClientResult.Success)
{
Console.WriteLine("File deleted successfully.");
}
else
{
Console.WriteLine("File deletion failed.");
}
Error Handling
Both PutObjectAsync
methods handle exceptions from:
- AmzonS3Exception: Errors specific to the S3 service, such as invalid bucket names or key.
- General Exceptions: Catches other runtime errors.
Logging Errors
Inspect the returned S3ClientResult.Failed
to log or handle errors:
if (result == S3ClientResult.Failed)
{
Console.WriteLine($"Error: {result.Errors}");
}
Notes
- Dependencies: Ensure Cloudflare R2 credentials and endpoint are valid.
- Bucket Policy: Verify that the target bucket has appropriate permissions.
- Existence Check: The
DeleteObjectAsync
method useS3Client.IsFileExists
to confirm file existence before deletion.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net8.0
- AWSSDK.S3 (>= 3.7.406.3)
- Microsoft.Extensions.Configuration.Json (>= 8.0.1)
- Microsoft.Extensions.Options (>= 8.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.