Junaid
Junaid

Reputation: 1030

Deleting a file from a sub directory of an AWS S3 bucket using asp.net

I want to delete a file that resides on the path: bucket1/dir1/dir2/file.png

The code I have done:

public bool DeleteFileFromS3(string bucketName, string directoryInBucket, string subDirectoryInDirectory, string fileNameInS3) 
{
    IAmazonS3 client = new AmazonS3Client(RegionEndpoint.USEast2);
    var BucketName = "";

    if (directoryInBucket == "" || directoryInBucket == null)
    {
        BucketName = bucketName; //no subdirectory just bucket name  
    }
    else
    {   // subdirectory and bucket name  
        BucketName = bucketName + @"/" + directoryInBucket + @"/" + subDirectoryInDirectory;
    }

    var objectName = fileNameInS3;

    client.DeleteObject(BucketName, objectName); 

    return true; //indicate that the file was sent 
}

However, this doesn't work.

Upon some research, I found out that the AWS file system is different. It is object-based and the files are stored as objects with keys. However, I am unable to find an example that uses keys for a file that resides in the subdirectory of a bucket and then deletes it using them. Kindly suggest me something.

Upvotes: 0

Views: 1054

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269520

The BucketName should only contain the name of the bucket.

The ObjectName should include the name of the object, with the full path to the object.

For example:

  • BucketName = 'my-bucket'
  • ObjectName = 'invoices/january/foo.txt'

This is because Amazon S3 doesn't really have directories, even though it 'appears' to have them. The full path is part of the object name ('Key').

Upvotes: 1

Related Questions