Amazon S3 Bucket Management with C#: Part 8 – Deleting a file in a Bucket

Before getting started

Skill Level: Beginner

Assumptions:

  1. You already gone through Parts 1-7 of Managing Amazon AWS with C#.

Additional information: I sometimes cover small sub-topics in a post. Along with AWS, you will also be exposed to:

  • Rhyous.SimpleArgs
  • Don’t Repeat Yourself (DRY) Principal

Step 1 – Add a DeleteFile method to BucketManager.cs

  1. Edit file called BucketManager.cs.
  2. Enter this new method:
            public static async Task CreateTextFile(AmazonS3Client client, string bucketName, string filename, string text)
            {
                var dirRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = filename,
                    InputStream = text.ToStream()
                };
                await client.PutObjectAsync(dirRequest);
                Console.WriteLine($"Created text file in S3 bucket: {bucketName}/{filename}");
            }
    

Notice: The code is almost identical to that of deleting a directory, with only one exception. We aren’t ending with a /. We really should not have duplicate code. So lets fix this in the next step.

Step 2 – Solve the Repetitive Code

It is best practice to avoid having duplicate code. This is often called the “Don’t Repeat Yourself” principal. So let’s update the DeleteBucketDirectory code to forward to the DeleteFile code.

  1. Update the DeleteDirectory method so that both methods share code.
           public static async Task DeleteBucketDirectory(AmazonS3Client client, string bucketName, string directory)
            {
                if (!directory.EndsWith("/"))
                    directory = directory += "/";
                await DeleteFile(client, bucketName, directory);
            }
    

Now the delete directory code is no longer repetitive. A directory is the same as a file, just with a slash. So the Delete directory correctly makes sure that the directory name ends with a slash, then forwards the call to delete file.

Step 3 – Update the Action Argument

We should be very good at this by now. We need to make this method a valid action for the Action Argument.

  1. Edit the ArgsHandler.cs file to define an Action argument.
                        ...
                        AllowedValues = new ObservableCollection<string>
                        {
                            "CreateBucket",
                            "DeleteBucket",
                            "ListFiles",
                            "UploadFile",
                            "CreateBucketDirectory",
                            "DeleteBucketDirectory",
                            "CreateTextFile",
                            "DeleteFile"
                        },
                        ...
    

Note: There are no additional Arguments to add. To delete a file, we need the bucket name and a file name, which we already have Arguments for.

Step 4 – Fix the parameter mismatch problem

In Part 4, we created a method to pass different parameters to different methods. Let’s use that to pass in the correct parameters.

However, take note that we now have more exceptions than we had commonalities. This suggests that it is about time to refactor this code. For now, we will leave it.

            // Use the Custom or Common pattern
            CustomParameters.Add("UploadFile", new object[] { transferUtility, bucketName, Args.Value("File") });
            CustomParameters.Add("CreateBucketDirectory", new object[] { s3client, bucketName, Args.Value("Directory") });
            CustomParameters.Add("DeleteBucketDirectory", new object[] { s3client, bucketName, Args.Value("Directory") });
            CustomParameters.Add("CreateTextFile", new object[] { s3client, bucketName, Args.Value("Filename"), Args.Value("Text") });

You can now add a text file to an Amazon S3 bucket using C#.

Homework: There is some repetitiveness between CreateFolder and DeleteFolder. What is it? (Hint: Directories end with a slash.)

Go to: Part 9 – Uploading a file with its path to a Bucket

Return to: Managing Amazon AWS with C#

Leave a Reply

How to post code in comments?