I was having a difficult time finding an example of working with S3 files using the .NET SDK. There are examples, but they did not include how to authenticate the client. As someone completely new to working with S3 (particularly the SDK), I wasn’t sure exactly how to initialize my client instance with my credentials, so I made a quick, all-encompassing example.
This does require the AWSSDK.Core and AWSSDK.S3 NuGet packages to be installed.
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace BinaryDad.AmazonS3
{
internal class Program
{
internal const string bucketName = "YOURBUCKETNAME";
// IAM credentials
internal const string accessKey = "YOURACCESSKEY";
internal const string secretKey = "YOURSECRETKEY";
private static readonly IDictionary<string, string> mimeTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["docx"] = "application / vnd.openxmlformats - officedocument.wordprocessingml.document",
["pdf"] = "application/pdf"
// grow as needed
};
private static void Main(string[] args)
{
Main().Wait();
}
private static async Task Main()
{
var credentials = new BasicAWSCredentials(accessKey, secretKey);
var client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);
#region Upload file
var filePath = @"C:\path\to\file.pdf";
var fileName = Path.GetFileName(filePath); // file name (or key), can also contain a folder, such as "folder/to/file.pdf"
var mimeType = GetMimeType(fileName);
var uploadRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = fileName, // a key to represent the file, typically the filename (can contain folder)
FilePath = filePath, // full file path to upload
ContentType = mimeType
};
// optional - add metadata for the upload file
uploadRequest.Metadata.Add("mime-type", mimeType);
uploadRequest.Metadata.Add("uploaded-by", "ryan");
var uploadResponse = await client.PutObjectAsync(uploadRequest);
#endregion
#region Download file
var downloadRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = fileName
};
using (var response = await client.GetObjectAsync(downloadRequest))
{
var uploadedBy = response.Metadata["uploaded-by"];
var type = response.Metadata["mime-type"];
// copy stream to file
using (var file = File.OpenWrite(@"C:\path\to\downloaded-file.pdf"))
{
await response.ResponseStream.CopyToAsync(file);
}
}
#endregion
}
private static string GetMimeType(string fileName)
{
var extension = Path.GetExtension(fileName).TrimStart('.');
if (mimeTypes.TryGetValue(extension, out var mimeType))
{
return mimeType;
}
// default for files
return "application/octet-stream";
}
}
}
This is day 2 of #100DaysToOffload.
Leave a Reply