Amazon S3: Copy an Object Using Multipart Copy
See more S3 - REST Examples
Copy an object inside a general purpose bucket without downloading it. Initiate a destination upload, issue UploadPartCopy ranges, and complete it with the exact returned ETags. Requires source read and destination write permissions, plus applicable KMS permissions. HTTP 200 copy/completion bodies are checked for embedded errors.
The example uses 1,000,000,000-byte parts and supports objects larger than 5 MiB through 10,000,000,000,000 bytes (10 TB), with up to 10,000 parts. Decimal-string offset construction avoids int64 and 32-bit overflow. This is an example limit, not S3’s maximum object size; larger objects require larger parts. Only the final part may be below 5 MiB.
A source version is pinned when returned by HEAD, and every part uses the original ETag condition. Choose a distinct destination key; completing can replace that key or create a new version. Metadata and tags are not automatically inherited by multipart initiation; set the desired destination metadata, content type and encryption there. The source remains unchanged.
The saved s3-multipart.json can be used with the existing abort example after a failure. Completion XML is saved only after all copy parts succeed. Do not restart into the same state file blindly; an uncertain initiation/completion needs inspection. This example does not implement selective resume, and incomplete parts incur charges until completed or aborted.
For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.
Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.
Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.
Chilkat C# Downloads
bool success = false;
// StringBuilder compares text by value in every generated language.
Chilkat.StringBuilder textCompare = new Chilkat.StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the S3 operation.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/s3.json");
if (success != true) {
Debug.WriteLine("Could not load private AWS credentials.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.StringOf("access_key"));
bool sameText1 = textCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (sameText1 == true)) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.StringOf("secret_key"));
bool sameText2 = textCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (sameText2 == true)) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
// General purpose bucket in the commercial AWS partition.
string region = "us-west-2";
string bucketName = "amzn-s3-demo-bucket";
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
success = endpoint.Append(bucketName);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = endpoint.Append(".");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = endpoint.Append("s3.");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = endpoint.Append(region);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = endpoint.Append(".amazonaws.com");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
Chilkat.AuthAws aws = new Chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "s3";
aws.SignatureVersion = 4;
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("Could not configure AWS signing.");
return;
}
// Temporary credentials require this token in every signed query.
// Keep request URLs private. Do not clear this parameter between requests.
if (credentials.HasMember("session_token") == true) {
if (credentials.JsonTypeOf("session_token") != 1) {
Debug.WriteLine("session_token must be a string.");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.StringOf("session_token"));
bool sameText3 = textCompare.ContentsEqual("",true);
if (sameText3 != true) {
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Debug.WriteLine("Could not attach the TLS connection.");
return;
}
Chilkat.Xml xml = new Chilkat.Xml();
xml.Strict = true;
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
string objectKey = "documents/source.bin";
Chilkat.StringBuilder objectPath = new Chilkat.StringBuilder();
success = objectPath.Append(objectKey);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = objectPath.Encode("url_rfc3986","utf-8");
if (success != true) {
Debug.WriteLine("Could not encode the object key.");
return;
}
int restoredSlashes = objectPath.Replace("%2F","/");
success = objectPath.Prepend("/");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.SendReqNoBody("HEAD",objectPath.GetAsString());
if (success != true) {
Debug.WriteLine("Could not send HEAD request.");
return;
}
int statusCode = rest.ReadResponseHeader();
if (statusCode < 0) {
Debug.WriteLine("Could not read the response header.");
return;
}
if (statusCode != 200) {
Debug.WriteLine("HEAD did not return HTTP 200. A 403 is not proof that an object is missing.");
return;
}
// HEAD has no response body; do not call a body-reading method.
string sourceEtag = rest.ResponseHdrByName("ETag");
textCompare.Clear();
textCompare.SetString(sourceEtag);
bool sameText4 = textCompare.ContentsEqual("",true);
if ((rest.LastMethodSuccess != true) || (sameText4 == true)) {
Debug.WriteLine("Missing response header: ETag");
return;
}
string sourceSize = rest.ResponseHdrByName("Content-Length");
textCompare.Clear();
textCompare.SetString(sourceSize);
bool sameText5 = textCompare.ContentsEqual("",true);
if ((rest.LastMethodSuccess != true) || (sameText5 == true)) {
Debug.WriteLine("Missing response header: Content-Length");
return;
}
string sourceVersion = rest.ResponseHdrByName("x-amz-version-id");
if (rest.LastMethodSuccess != true) {
sourceVersion = "";
}
// Split a decimal size into billions and a remainder. No large integer type.
Chilkat.StringBuilder sizeText = new Chilkat.StringBuilder();
Chilkat.StringBuilder digits = new Chilkat.StringBuilder();
Chilkat.StringBuilder piece = new Chilkat.StringBuilder();
success = sizeText.Append(sourceSize);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = digits.Append("0123456789");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
if ((sizeText.Length < 1) || (sizeText.Length > 14)) {
Debug.WriteLine("Invalid source length for this example.");
return;
}
int position = 0;
while ((position < sizeText.Length)) {
string digit = sizeText.GetRange(position,1,false);
if (digits.Contains(digit,true) != true) {
Debug.WriteLine("Source length is not decimal.");
return;
}
position = position + 1;
}
int fullBillions = 0;
int tailBytes = 0;
if (sizeText.Length > 9) {
success = piece.SetString(sizeText.GetRange(0,sizeText.Length - 9,false));
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
fullBillions = piece.IntValue;
success = piece.SetString(sizeText.GetRange(sizeText.Length - 9,9,false));
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
tailBytes = piece.IntValue;
}
else {
tailBytes = sizeText.IntValue;
}
int numParts = fullBillions;
if (tailBytes > 0) {
numParts = numParts + 1;
}
if ((numParts < 1) || (numParts > 10000)) {
Debug.WriteLine("This example supports objects through 10 TB using 1 GB parts.");
return;
}
if ((fullBillions == 0) && (tailBytes <= 5242880)) {
Debug.WriteLine("Use CopyObject for sources of 5 MiB or less; ranged copy requires a larger source.");
return;
}
Chilkat.FileAccess files = new Chilkat.FileAccess();
if (files.FileExists("s3-multipart.json") == true) {
Debug.WriteLine("A multipart state file already exists; finish or abort that upload first.");
return;
}
Chilkat.StringBuilder copySource = new Chilkat.StringBuilder();
success = copySource.Append("/");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = copySource.Append(bucketName);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = copySource.Append(objectPath.GetAsString());
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
textCompare.Clear();
textCompare.SetString(sourceVersion);
bool sameText6 = textCompare.ContentsEqual("",true);
if (sameText6 != true) {
Chilkat.StringBuilder encodedVersion = new Chilkat.StringBuilder();
success = encodedVersion.Append(sourceVersion);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = encodedVersion.Encode("url_rfc3986","utf-8");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = copySource.Append("?versionId=");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = copySource.Append(encodedVersion.GetAsString());
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
}
// Destination is a DIFFERENT key in this bucket. Existing destination is replaced.
string destinationKey = "documents/copy.bin";
textCompare.Clear();
textCompare.SetString(destinationKey);
bool sameText7 = textCompare.ContentsEqual(objectKey,true);
if (sameText7 == true) {
Debug.WriteLine("Choose a destination key different from the source.");
return;
}
success = objectPath.SetString(destinationKey);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = objectPath.Encode("url_rfc3986","utf-8");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
int destinationSlashes = objectPath.Replace("%2F","/");
success = objectPath.Prepend("/");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddQueryParam("uploads","");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("Content-Type","application/octet-stream");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
string responseBody = rest.FullRequestNoBody("POST",objectPath.GetAsString());
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("S3 HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText8 = textCompare.ContentsEqual("Error",true);
if ((success == true) && (sameText8 == true)) {
Debug.WriteLine("S3 error code: " + xml.GetChildContent("Code"));
}
// Keep signed headers, credentials, URLs, and full diagnostics private.
// A timeout may leave a write's outcome uncertain. Check before retrying.
return;
}
success = xml.LoadXml(responseBody);
if (success != true) {
Debug.WriteLine("Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText9 = textCompare.ContentsEqual("InitiateMultipartUploadResult",true);
if (sameText9 != true) {
Debug.WriteLine("Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.GetChildContent("UploadId"));
bool sameText10 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("UploadId") != true) || (sameText10 == true)) {
Debug.WriteLine("Missing response field: UploadId");
return;
}
string uploadId = xml.GetChildContent("UploadId");
Chilkat.JsonObject state = new Chilkat.JsonObject();
success = state.UpdateString("bucket",bucketName);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("region",region);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("key",destinationKey);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("upload_id",uploadId);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("source_key",objectKey);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("source_etag",sourceEtag);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.UpdateString("source_size",sourceSize);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.WriteFile("s3-multipart.json");
if (success != true) {
Debug.WriteLine("Upload initiated but saving state failed; recover the upload ID or list unfinished uploads.");
return;
}
success = rest.RemoveQueryParam("uploads");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.RemoveHeader("Content-Type");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddQueryParam("uploadId",uploadId);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source",copySource.GetAsString());
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source-if-match",sourceEtag);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
Chilkat.Xml parts = new Chilkat.Xml();
parts.Tag = "CompleteMultipartUpload";
Chilkat.StringBuilder range = new Chilkat.StringBuilder();
Chilkat.StringBuilder ending = new Chilkat.StringBuilder();
Chilkat.StringBuilder number = new Chilkat.StringBuilder();
int partNumber = 1;
while ((partNumber <= numParts)) {
range.Clear();
ending.Clear();
number.Clear();
success = range.Append("bytes=");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
if (partNumber == 1) {
success = range.Append("0");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
}
else {
success = range.AppendInt(partNumber - 1);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = range.Append("000000000");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
}
success = range.Append("-");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
if (partNumber <= fullBillions) {
if (partNumber > 1) {
success = ending.AppendInt(partNumber - 1);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
success = ending.Append("999999999");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
}
else {
success = ending.AppendInt(tailBytes - 1);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
if (fullBillions > 0) {
while ((ending.Length < 9)) {
success = ending.Prepend("0");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
success = number.AppendInt(fullBillions);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = ending.Prepend(number.GetAsString());
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
}
success = range.Append(ending.GetAsString());
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
number.Clear();
success = number.AppendInt(partNumber);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
if (partNumber > 1) {
success = rest.RemoveQueryParam("partNumber");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-range");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
success = rest.AddQueryParam("partNumber",number.GetAsString());
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-copy-source-range",range.GetAsString());
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
responseBody = rest.FullRequestNoBody("PUT",objectPath.GetAsString());
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("S3 HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText11 = textCompare.ContentsEqual("Error",true);
if ((success == true) && (sameText11 == true)) {
Debug.WriteLine("S3 error code: " + xml.GetChildContent("Code"));
}
// Keep signed headers, credentials, URLs, and full diagnostics private.
// A timeout may leave a write's outcome uncertain. Check before retrying.
return;
}
success = xml.LoadXml(responseBody);
if (success != true) {
Debug.WriteLine("Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText12 = textCompare.ContentsEqual("CopyPartResult",true);
if (sameText12 != true) {
Debug.WriteLine("Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.GetChildContent("ETag"));
bool sameText13 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("ETag") != true) || (sameText13 == true)) {
Debug.WriteLine("Missing response field: ETag");
return;
}
parts.I = partNumber - 1;
parts.UpdateChildContentInt("Part[i]|PartNumber",partNumber);
parts.UpdateChildContent("Part[i]|ETag",xml.GetChildContent("ETag"));
Debug.WriteLine("Copied part: " + Convert.ToString(partNumber));
partNumber = partNumber + 1;
}
success = state.UpdateString("completion_xml",parts.GetXml());
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = state.WriteFile("s3-multipart.json");
if (success != true) {
Debug.WriteLine("Parts copied but completion state could not be saved.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-if-match");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.RemoveHeader("x-amz-copy-source-range");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.RemoveQueryParam("partNumber");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("Content-Type","application/xml");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
responseBody = rest.FullRequestString("POST",objectPath.GetAsString(),parts.GetXml());
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately.");
return;
}
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("S3 HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = xml.LoadXml(responseBody);
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText14 = textCompare.ContentsEqual("Error",true);
if ((success == true) && (sameText14 == true)) {
Debug.WriteLine("S3 error code: " + xml.GetChildContent("Code"));
}
// Keep signed headers, credentials, URLs, and full diagnostics private.
// A timeout may leave a write's outcome uncertain. Check before retrying.
return;
}
success = xml.LoadXml(responseBody);
if (success != true) {
Debug.WriteLine("Expected well-formed XML.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.Tag);
bool sameText15 = textCompare.ContentsEqual("CompleteMultipartUploadResult",true);
if (sameText15 != true) {
Debug.WriteLine("Unexpected S3 response element; this is not a successful result.");
return;
}
textCompare.Clear();
textCompare.SetString(xml.GetChildContent("ETag"));
bool sameText16 = textCompare.ContentsEqual("",true);
if ((xml.HasChildWithTag("ETag") != true) || (sameText16 == true)) {
Debug.WriteLine("Missing response field: ETag");
return;
}
Debug.WriteLine("Multipart copy completed; source was not deleted.");
// Archive s3-multipart.json after confirming the destination.