AWS services like S3 from C#

 The AWS SDK for .NET is the primary way to interact with AWS services like S3 from C#. You'll need to install the AWSSDK.S3 NuGet package in your project.

Here's a breakdown of common S3 operations and the C# code to perform them:

First, install the necessary NuGet package:

Bash
Install-Package AWSSDK.S3 

Now, let's look at the C# code examples.


...............................................

using Amazon.S3;

using Amazon.S3.Model;

using System;

using System.IO;

using System.Threading.Tasks;


public class S3Connector

{

    private readonly IAmazonS3 _s3Client;

    private readonly string _bucketName;


    /// <summary>

    /// Initializes a new instance of the S3Connector class.

    /// </summary>

    /// <param name="accessKey">Your AWS Access Key ID.</param>

    /// <param name="secretKey">Your AWS Secret Access Key.</param>

    /// <param name="bucketName">The name of the S3 bucket to interact with.</param>

    /// <param name="region">The AWS region where your S3 bucket is located.</param>

    public S3Connector(string accessKey, string secretKey, string bucketName, Amazon.RegionEndpoint region)

    {

        // It's highly recommended to use IAM roles for production environments

        // instead of hardcoding credentials directly in your application.

        _s3Client = new AmazonS3Client(accessKey, secretKey, region);

        _bucketName = bucketName;

    }


    /// <summary>

    /// Lists all objects in the specified S3 bucket.

    /// </summary>

    public async Task ListObjectsAsync()

    {

        try

        {

            // Create a request to list objects in the bucket.

            ListObjectsV2Request request = new ListObjectsV2Request

            {

                BucketName = _bucketName

            };


            // Execute the request asynchronously.

            ListObjectsV2Response response = await _s3Client.ListObjectsV2Async(request);


            Console.WriteLine($"Objects in bucket '{_bucketName}':");

            // Iterate through the retrieved S3 objects and print their keys and sizes.

            foreach (S3Object obj in response.S3Objects)

            {

                Console.WriteLine($"  - {obj.Key} (Size: {obj.Size} bytes)");

            }

        }

        catch (AmazonS3Exception e)

        {

            // Catch specific AWS S3 exceptions and print the error message.

            Console.WriteLine($"Error listing objects: {e.Message}");

        }

        catch (Exception e)

        {

            // Catch any other unexpected exceptions.

            Console.WriteLine($"An unexpected error occurred: {e.Message}");

        }

    }


    /// <summary>

    /// Uploads a file from a local path to the S3 bucket.

    /// </summary>

    /// <param name="filePath">The full path to the local file to upload.</param>

    /// <param name="keyName">The key (object name) that the file will have in S3.</param>

    public async Task UploadFileAsync(string filePath, string keyName)

    {

        try

        {

            // Create a request to put an object into the bucket.

            PutObjectRequest request = new PutObjectRequest

            {

                BucketName = _bucketName,

                Key = keyName,

                FilePath = filePath // Specify the local file path to upload

            };


            // Execute the upload request asynchronously.

            PutObjectResponse response = await _s3Client.PutObjectAsync(request);


            Console.WriteLine($"Successfully uploaded '{filePath}' to '{_bucketName}/{keyName}'. ETag: {response.ETag}");

        }

        catch (AmazonS3Exception e)

        {

            Console.WriteLine($"Error uploading file: {e.Message}");

        }

        catch (Exception e)

        {

            Console.WriteLine($"An unexpected error occurred: {e.Message}");

        }

    }


    /// <summary>

    /// Downloads an object from the S3 bucket to a specified local file path.

    /// </summary>

    /// <param name="keyName">The key (object name) of the file in S3 to download.</param>

    /// <param name="downloadPath">The local path where the downloaded file will be saved.</param>

    public async Task DownloadFileAsync(string keyName, string downloadPath)

    {

        try

        {

            // Create a request to get an object from the bucket.

            GetObjectRequest request = new GetObjectRequest

            {

                BucketName = _bucketName,

                Key = keyName

            };


            // Execute the download request asynchronously.

            // Use 'using' statements to ensure streams are properly disposed after use.

            using (GetObjectResponse response = await _s3Client.GetObjectAsync(request))

            using (Stream responseStream = response.ResponseStream) // The stream containing the object's data

            using (FileStream fileStream = File.Create(downloadPath)) // The local file stream to write to

            {

                // Copy the content from the S3 response stream to the local file stream.

                await responseStream.CopyToAsync(fileStream);

            }


            Console.WriteLine($"Successfully downloaded '{keyName}' from '{_bucketName}' to '{downloadPath}'.");

        }

        catch (AmazonS3Exception e)

        {

            Console.WriteLine($"Error downloading file: {e.Message}");

        }

        catch (Exception e)

        {

            Console.WriteLine($"An unexpected error occurred: {e.Message}");

        }

    }


    /// <summary>

    /// Deletes a specific object from the S3 bucket.

    /// </summary>

    /// <param name="keyName">The key (object name) of the file to delete from S3.</param>

    public async Task DeleteObjectAsync(string keyName)

    {

        try

        {

            // Create a request to delete an object.

            DeleteObjectRequest request = new DeleteObjectRequest

            {

                BucketName = _bucketName,

                Key = keyName

            };


            // Execute the delete request asynchronously.

            await _s3Client.DeleteObjectAsync(request);


            Console.WriteLine($"Successfully deleted '{keyName}' from '{_bucketName}'.");

        }

        catch (AmazonS3Exception e)

        {

            Console.WriteLine($"Error deleting object: {e.Message}");

        }

        catch (Exception e)

        {

            Console.WriteLine($"An unexpected error occurred: {e.Message}");

        }

    }


    /// <summary>

    /// Creates a new S3 bucket. Note: Bucket names must be globally unique across all of AWS.

    /// </summary>

    /// <param name="newBucketName">The name of the new bucket to create.</param>

    public async Task CreateBucketAsync(string newBucketName)

    {

        try

        {

            // Create a request to put a new bucket.

            PutBucketRequest request = new PutBucketRequest

            {

                BucketName = newBucketName,

                // Set the Access Control List (ACL) for the new bucket.

                // S3CannedACL.Private means only the owner has access.

                CannedACL = S3CannedACL.Private

            };


            // Execute the create bucket request asynchronously.

            await _s3Client.PutBucketAsync(request);

            Console.WriteLine($"Bucket '{newBucketName}' created successfully.");

        }

        catch (AmazonS3Exception e)

        {

            // Handle cases where the bucket already exists.

            if (e.ErrorCode == "BucketAlreadyOwnedByYou")

            {

                Console.WriteLine($"Bucket '{newBucketName}' already exists and is owned by you.");

            }

            else

            {

                Console.WriteLine($"Error creating bucket: {e.Message}");

            }

        }

        catch (Exception e)

        {

            Console.WriteLine($"An unexpected error occurred: {e.Message}");

        }

    }

}


public class Program

{

    public static async Task Main(string[] args)

    {

        // IMPORTANT: Replace these placeholders with your actual AWS credentials and bucket details.

        // For production applications, avoid hardcoding credentials.

        // Consider using IAM roles, environment variables, or shared credential files.

        string awsAccessKey = "YOUR_AWS_ACCESS_KEY";

        string awsSecretKey = "YOUR_AWS_SECRET_KEY";

        string bucketName = "your-unique-s3-bucket-name"; // This name must be globally unique across AWS

        Amazon.RegionEndpoint awsRegion = Amazon.RegionEndpoint.EUWest1; // Example: eu-west-1 (Ireland)


        // Create an instance of the S3Connector.

        S3Connector connector = new S3Connector(awsAccessKey, awsSecretKey, bucketName, awsRegion);


        Console.WriteLine("--- Listing Objects ---");

        await connector.ListObjectsAsync();


        Console.WriteLine("\n--- Uploading File ---");

        string localFilePath = "test_file.txt"; // Define a local dummy file for testing purposes

        // Create the dummy file with some content.

        File.WriteAllText(localFilePath, "Hello, S3 from C#! This is a test file for upload.");

        string s3Key = "my-test-object.txt"; // The name it will have in S3

        await connector.UploadFileAsync(localFilePath, s3Key);


        Console.WriteLine("\n--- Listing Objects After Upload ---");

        await connector.ListObjectsAsync();


        Console.WriteLine("\n--- Downloading File ---");

        string downloadPath = "downloaded_test_file.txt"; // Path to save the downloaded file

        await connector.DownloadFileAsync(s3Key, downloadPath);

        // Read and display the content of the downloaded file to verify.

        Console.WriteLine($"Content of downloaded file: {File.ReadAllText(downloadPath)}");


        Console.WriteLine("\n--- Deleting Object ---");

        await connector.DeleteObjectAsync(s3Key);


        Console.WriteLine("\n--- Listing Objects After Deletion ---");

        await connector.ListObjectsAsync();


        // Uncomment the following lines to test bucket creation.

        // Remember that bucket names must be globally unique.

        // Console.WriteLine("\n--- Creating a New Bucket (Optional) ---");

        // string newBucketToCreate = "my-brand-new-unique-bucket-12345";

        // await connector.CreateBucketAsync(newBucketToCreate);


        // Clean up the locally created test files.

        if (File.Exists(localFilePath))

        {

            File.Delete(localFilePath);

        }

        if (File.Exists(downloadPath))

        {

            File.Delete(downloadPath);

        }


        Console.WriteLine("\nOperations completed. Please ensure you remove any test buckets or objects from S3 if you created them.");

    }

}


No comments: