Reputation: 787
Is there any way to move an object to a different folder in the same bucket using the AWS SDK (preferably for .Net)?
Searching around all I can see is the suggestion of Copy to new location and Delete of the original (Which is easy enough via "CopyObjectRequest" and "DeleteObjectRequest") however I'm just wondering is this the only way?
Upvotes: 21
Views: 46341
Reputation: 1114
As @user1527762 mentions S3FileInfo is not available in .NET Core version of the AWSSDK.S3 library (v 3.7.2.2).
If you are in .net core you can use the CopyObject to move an object from one bucket to another.
var s3Client = new AmazonS3Client(RegionEndpoint.USEast1);
var copyRequest = new CopyObjectRequest
{
SourceBucket = "source-bucket",
SourceKey = "fileName",
DestinationBucket = "dest-bucket",
DestinationKey = "fileName.jpg",
CannedACL = S3CannedACL.PublicRead,
};
var copyResponse = await s3Client.CopyObjectAsync(copyRequest);
CopyObject does not delete the source object so you would have to call delete like this:
DeleteObjectRequest request = new DeleteObjectRequest
{
BucketName = "source-bucket",
Key = "fileName.jpg"
};
await s3Client .DeleteObjectAsync(request);
Details on CopyObject here: https://docs.aws.amazon.com/AmazonS3/latest/userguide/copy-object.html
And DeleteObject here: https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-objects.html
Upvotes: 7
Reputation: 787
Turns out you can use Amazon.S3.IO.S3FileInfo to get the object and then call the "MoveTo" method to move the object.
S3FileInfo currentObject = new S3FileInfo(S3Client,Bucket,CurrentKey);
S3FileInfo movedObject = currentObject.MoveTo(Bucket,NewKey);
EDIT: It turns out the above "MoveTo" method just performs a Copy and Delete behind the scenes anyway :)
For further information:
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html?page=S3/TS3IOS3FileInfo.html&tocid=Amazon_S3_IO_S3FileInfo
Upvotes: 23