S3: Delete Multiple Objects and Check Per-Object Errors
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.
The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.
Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.
Chilkat C# Downloads
bool success = false;
Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load private credentials; never put access keys or session tokens in source.
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 S3 credentials.");
return;
}
stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
Chilkat.Http http = new Chilkat.Http();
http.AwsAccessKey = credentials.StringOf("access_key");
http.AwsSecretKey = credentials.StringOf("secret_key");
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.StringOf("session_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
Debug.WriteLine("session_token must be a nonempty string when supplied.");
return;
}
http.AwsSessionToken = credentials.StringOf("session_token");
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
string region = "us-west-2";
http.AwsRegion = region;
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("s3.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
http.AwsEndpoint = endpoint.GetAsString();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
// A region redirect is not success. Correct the endpoint and signing region.
string bucketName = "your-bucket-name";
Chilkat.Xml deleteRequest = new Chilkat.Xml();
deleteRequest.Tag = "Delete";
deleteRequest.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
deleteRequest.UpdateChildContent("Quiet","true");
// XML APIs escape key text. Do NOT URL-encode keys in this XML body.
deleteRequest.UpdateChildContent("Object[0]|Key","images/seahorse.jpg");
deleteRequest.UpdateChildContent("Object[1]|Key","images/starfish.jpg");
// For permanent deletion of a specific version, add Object[i]|VersionId
// deliberately. Use separate XML elements, not an embedded string convention.
if ((deleteRequest.NumChildrenHavingTag("Object") < 1) || (deleteRequest.NumChildrenHavingTag("Object") > 1000)) {
Debug.WriteLine("Use a batch of 1 to 1,000 object identifiers.");
return;
}
string requestBody = deleteRequest.GetXml();
// 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(bucketName);
host.Append(".");
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) {
signedHeaders.Append(";x-amz-security-token");
canonical.Append("x-amz-security-token:");
canonical.Append(credentials.StringOf("session_token"));
canonical.Append("\n");
http.SetRequestHeader("x-amz-security-token",credentials.StringOf("session_token"));
}
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);
http.SetRequestHeader("Authorization",authorization.GetAsString());
http.SetRequestHeader("Content-MD5",contentMd5);
http.SetRequestHeader("x-amz-content-sha256",payloadHash);
http.SetRequestHeader("x-amz-date",amzDate);
Chilkat.StringBuilder requestUrl = new Chilkat.StringBuilder();
requestUrl.Append("https://");
requestUrl.Append(host.GetAsString());
requestUrl.Append("/?delete=");
Chilkat.HttpResponse response = new Chilkat.HttpResponse();
success = http.HttpStr("POST",requestUrl.GetAsString(),requestBody,"utf-8","application/xml",response);
if (success != true) {
Debug.WriteLine("Request failed (transport or S3 error). HTTP status: " + Convert.ToString(http.LastStatus));
// Inspect LastErrorText privately. Do not log credentials or signed URLs.
return;
}
if (response.StatusCode != 200) {
Debug.WriteLine("Unexpected HTTP status: " + Convert.ToString(response.StatusCode));
return;
}
// HTTP 200 can contain per-object errors. Inspect the actual XML body.
Chilkat.Xml xml = new Chilkat.Xml();
success = xml.LoadXml(response.BodyStr);
if (success != true) {
Debug.WriteLine("Invalid XML response.");
return;
}
stringCompare.SetString(xml.Tag);
bool stringMatch4 = stringCompare.ContentsEqual("DeleteResult",true);
if (stringMatch4 != true) {
Debug.WriteLine("Unexpected XML response root.");
return;
}
int failures = xml.NumChildrenHavingTag("Error");
int i = 0;
while ((i < failures)) {
xml.I = i;
Debug.WriteLine("Failed key: " + xml.GetChildContent("Error[i]|Key"));
Debug.WriteLine("Error code: " + xml.GetChildContent("Error[i]|Code"));
i = i + 1;
}
if (failures != 0) {
Debug.WriteLine("One or more objects were not deleted. Retry only appropriate failed identifiers.");
return;
}
// Quiet=true means success entries need not be returned.
Debug.WriteLine("Delete batch succeeded with no reported object errors.");