Amazon S3: Delete Multiple Objects and Check Each Result
See more S3 - REST Examples
Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.
Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.
General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.
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.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
// 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;
rest.Host = endpoint.GetAsString();
if (credentials.HasMember("session_token") == true) {
if (credentials.JsonTypeOf("session_token") != 1) {
Debug.WriteLine("session_token must be a string.");
return;
}
}
// One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
Chilkat.JsonObject batch = new Chilkat.JsonObject();
batch.Strict = true;
success = batch.LoadFile("qa_data/aws/delete-objects.json");
if (success != true) {
Debug.WriteLine("Could not load the intended deletion batch.");
return;
}
int count = batch.SizeOfArray("objects");
if ((count < 1) || (count > 1000)) {
Debug.WriteLine("Supply 1 to 1000 objects in the batch.");
return;
}
xml.Tag = "Delete";
success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
xml.UpdateChildContent("Quiet","false");
Chilkat.Hashtable requested = new Chilkat.Hashtable();
Chilkat.JsonObject identity = new Chilkat.JsonObject();
int i = 0;
while ((i < count)) {
batch.I = i;
xml.I = i;
textCompare.Clear();
textCompare.SetString(batch.StringOf("objects[i].key"));
bool sameText3 = textCompare.ContentsEqual("",true);
if ((batch.JsonTypeOf("objects[i].key") != 1) || (sameText3 == true)) {
Debug.WriteLine("Each object needs a nonempty key.");
return;
}
string key = batch.StringOf("objects[i].key");
string version = "";
if (batch.HasMember("objects[i].version_id") == true) {
textCompare.Clear();
textCompare.SetString(batch.StringOf("objects[i].version_id"));
bool sameText4 = textCompare.ContentsEqual("",true);
if ((batch.JsonTypeOf("objects[i].version_id") != 1) || (sameText4 == true)) {
Debug.WriteLine("version_id must be a nonempty string when present.");
return;
}
version = batch.StringOf("objects[i].version_id");
xml.UpdateChildContent("Object[i]|VersionId",version);
}
xml.UpdateChildContent("Object[i]|Key",key);
success = identity.UpdateString("key",key);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = identity.UpdateString("version",version);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
string requestIdentity = identity.Emit();
if (requested.Contains(requestIdentity) == true) {
Debug.WriteLine("Duplicate key/version in deletion batch.");
return;
}
success = requested.AddInt(requestIdentity,1);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
i = i + 1;
}
string requestBody = xml.GetXml();
// Explicit signing is used only for this fixed request so Content-MD5 survives.
// Rest sends it; AuthAws must NOT also be configured on this Rest instance.
// Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
// Do not change signed headers, body, endpoint, or query after signing.
Chilkat.StringBuilder host = new Chilkat.StringBuilder();
host.Append(endpoint.GetAsString());
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
success = now.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read system time.");
return;
}
Chilkat.StringBuilder timestamp = new Chilkat.StringBuilder();
timestamp.Append(now.GetAsTimestamp(false));
int removedDashes = timestamp.Replace("-","");
int removedColons = timestamp.Replace(":","");
string amzDate = timestamp.GetAsString();
string dateStamp = timestamp.GetRange(0,8,false);
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
crypt.Charset = "utf-8";
crypt.HashAlgorithm = "md5";
crypt.EncodingMode = "base64";
string contentMd5 = crypt.HashStringENC(requestBody);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash delete body.");
return;
}
crypt.HashAlgorithm = "sha256";
crypt.EncodingMode = "hexlower";
string payloadHash = crypt.HashStringENC(requestBody);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash delete body.");
return;
}
Chilkat.StringBuilder signedHeaders = new Chilkat.StringBuilder();
signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date");
Chilkat.StringBuilder canonical = new Chilkat.StringBuilder();
canonical.Append("POST\n/\ndelete=\ncontent-md5:");
canonical.Append(contentMd5);
canonical.Append("\nhost:");
canonical.Append(host.GetAsString());
canonical.Append("\nx-amz-content-sha256:");
canonical.Append(payloadHash);
canonical.Append("\nx-amz-date:");
canonical.Append(amzDate);
canonical.Append("\n");
if (credentials.HasMember("session_token") == true) {
textCompare.Clear();
textCompare.SetString(credentials.StringOf("session_token"));
bool sameText5 = textCompare.ContentsEqual("",true);
if (sameText5 != true) {
signedHeaders.Append(";x-amz-security-token");
canonical.Append("x-amz-security-token:");
canonical.Append(credentials.StringOf("session_token"));
canonical.Append("\n");
success = rest.AddHeader("x-amz-security-token",credentials.StringOf("session_token"));
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
}
}
canonical.Append("\n");
canonical.Append(signedHeaders.GetAsString());
canonical.Append("\n");
canonical.Append(payloadHash);
string canonicalHash = crypt.HashStringENC(canonical.GetAsString());
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash canonical request.");
return;
}
Chilkat.StringBuilder scope = new Chilkat.StringBuilder();
scope.Append(dateStamp);
scope.Append("/");
scope.Append(region);
scope.Append("/s3/aws4_request");
Chilkat.StringBuilder stringToSign = new Chilkat.StringBuilder();
stringToSign.Append("AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append("\n");
stringToSign.Append(scope.GetAsString());
stringToSign.Append("\n");
stringToSign.Append(canonicalHash);
Chilkat.StringBuilder initialKey = new Chilkat.StringBuilder();
initialKey.Append("AWS4");
initialKey.Append(credentials.StringOf("secret_key"));
crypt.MacAlgorithm = "hmac";
success = crypt.SetMacKeyString(initialKey.GetAsString());
if (success != true) {
Debug.WriteLine("Could not set signing key.");
return;
}
string derivedKey = crypt.MacStringENC(dateStamp);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not derive date signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
Debug.WriteLine("Could not set derived signing key.");
return;
}
derivedKey = crypt.MacStringENC(region);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
Debug.WriteLine("Could not set derived signing key.");
return;
}
derivedKey = crypt.MacStringENC("s3");
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
Debug.WriteLine("Could not set derived signing key.");
return;
}
derivedKey = crypt.MacStringENC("aws4_request");
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not derive signing key.");
return;
}
success = crypt.SetMacKeyEncoded(derivedKey,"hex");
if (success != true) {
Debug.WriteLine("Could not set final signing key.");
return;
}
string signature = crypt.MacStringENC(stringToSign.GetAsString());
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not sign delete request.");
return;
}
Chilkat.StringBuilder authorization = new Chilkat.StringBuilder();
authorization.Append("AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.StringOf("access_key"));
authorization.Append("/");
authorization.Append(scope.GetAsString());
authorization.Append(", SignedHeaders=");
authorization.Append(signedHeaders.GetAsString());
authorization.Append(", Signature=");
authorization.Append(signature);
success = rest.AddHeader("Authorization",authorization.GetAsString());
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("Content-MD5",contentMd5);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-content-sha256",payloadHash);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddHeader("x-amz-date",amzDate);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
success = rest.AddQueryParam("delete","");
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
string responseBody = rest.FullRequestString("POST","/",requestBody);
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 sameText6 = textCompare.ContentsEqual("Error",true);
if ((success == true) && (sameText6 == 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 sameText7 = textCompare.ContentsEqual("DeleteResult",true);
if (sameText7 != true) {
Debug.WriteLine("Unexpected S3 response element; this is not a successful result.");
return;
}
int deleted = xml.NumChildrenHavingTag("Deleted");
int failed = xml.NumChildrenHavingTag("Error");
if (deleted + failed != count) {
Debug.WriteLine("Incomplete result: reconcile every requested object before retrying.");
return;
}
Chilkat.Hashtable received = new Chilkat.Hashtable();
int resultType = 0;
while ((resultType < 2)) {
string itemTag = "Deleted";
int resultCount = deleted;
if (resultType == 1) {
itemTag = "Error";
resultCount = failed;
}
int j = 0;
while ((j < resultCount)) {
xml.I = j;
Chilkat.StringBuilder itemPath = new Chilkat.StringBuilder();
success = itemPath.Append(itemTag);
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
success = itemPath.Append("[i]");
if (success != true) {
Debug.WriteLine("Could not build text.");
return;
}
Chilkat.Xml item = xml.FindChild(itemPath.GetAsString());
if (xml.LastMethodSuccess != true) {
Debug.WriteLine("Missing deletion result entry.");
return;
}
string resultKey = item.GetChildContent("Key");
string resultVersion = "";
if (item.HasChildWithTag("VersionId") == true) {
resultVersion = item.GetChildContent("VersionId");
}
success = identity.UpdateString("key",resultKey);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
success = identity.UpdateString("version",resultVersion);
if (success != true) {
Debug.WriteLine("Could not build saved state.");
return;
}
string responseIdentity = identity.Emit();
if ((requested.Contains(responseIdentity) != true) || (received.Contains(responseIdentity) == true)) {
Debug.WriteLine("Unexpected or duplicated deletion result; reconcile manually.");
return;
}
success = received.AddInt(responseIdentity,1);
if (success != true) {
Debug.WriteLine("Could not prepare the request.");
return;
}
Debug.WriteLine(itemTag + ": " + resultKey);
if (resultType == 1) {
Debug.WriteLine("Error code: " + item.GetChildContent("Code"));
}
j = j + 1;
}
resultType = resultType + 1;
}
if (failed > 0) {
Debug.WriteLine("Batch has per-object failures. Do not retry successful entries.");
return;
}
Debug.WriteLine("All requested deletions acknowledged.");