A couple of days ago, I wrote a python script and Bitbucket build pipeline that packaged a set of files from my repository into a zip file and then uploaded the zip file into an AWS S3 bucket. Thats one side done, so anytime my scripts change, I push to Bitbucket and that automatically updates my S3 bucket. Now its time to write the other side, the client that downloads the file from the S3 bucket and extracts it.
If your bucket is a public one, then anyone has access to the URL and so downloading it becomes easy. You can use the HttpClient class to easily download the file.
If access to the bucket is restricted, then you can use AWS APIs that are part of the AWS SDK for .NET, to download the file. That is what we will look into today:
Pre-Reqs:
In order to access the bucket, you have to have to authenticate with AWS. There are many ways to do that, in my case - I created an IAM user with programmatic access and gave him read permissions on my bucket (Refer this). Once you have done that, you will have the access key and the secret key for that user.
To work with AWS S3, Amazon has provided a set of APIs. You can either download and install the complete AWS SDK for .NET, or just install the AWSSDK.S3 package using NuGetPackage manager. To install just the AWS.S3 just open Visual Studio NuGet package manager, and search for AWSSDK.S3, then click the install option. Once installed, the NuGet Package manager will add a reference to your project automatically.
The Code
Now that you have your IAM user credentials and the AWSSDK.S3 package installed, lets focus on getting our zip file from S3 and extracting it.
First, create an instance of AmazonS3Config and specify the region name:
Then create an instance of AmazonS3Client class and pass your access key and secret key along with the using the AmazonS3Config object you just created.
If you know your bucket name, you create a ListObjectsRequest object with the bucket name and pass that to AmazonS3Client’s ListObjects()method. It’s as simple as this:
To download the object, you create a GetObjectRequest object with the bucket name and the object Key that you want to retrieve and then pass that to AmazonS3Client’s GetObject method. You can write the object to the file system using WriteResponseStreamToFile() method of the GetObjectResponse.
To Extract the zip file, you could use .NET’s built in ZipFile class. Be sure to add a reference to System.Io.Compression.FileSystem library, and add “using System.IO.Compression” to your namespace declarations.