Sample code for 30+ languages & platforms
VB.NET Requires Chilkat v11.6.0+

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.

AWS DeleteObjects reference

Chilkat VB.NET Downloads

VB.NET
Dim success As Boolean = False

'  StringBuilder compares text by value in every generated language.
Dim textCompare As 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.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
If (success <> True) Then
    Debug.WriteLine("Could not load private AWS credentials.")
    Exit Sub
End If

textCompare.Clear()
textCompare.SetString(credentials.StringOf("access_key"))
Dim sameText1 As Boolean = textCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (sameText1 = True)) Then
    Debug.WriteLine("Missing or invalid access_key.")
    Exit Sub
End If

textCompare.Clear()
textCompare.SetString(credentials.StringOf("secret_key"))
Dim sameText2 As Boolean = textCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (sameText2 = True)) Then
    Debug.WriteLine("Missing or invalid secret_key.")
    Exit Sub
End If

'  General purpose bucket in the commercial AWS partition.
Dim region As String = "us-west-2"
Dim bucketName As String = "amzn-s3-demo-bucket"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append(bucketName)
If (success <> True) Then
    Debug.WriteLine("Could not build text.")
    Exit Sub
End If

success = endpoint.Append(".")
If (success <> True) Then
    Debug.WriteLine("Could not build text.")
    Exit Sub
End If

success = endpoint.Append("s3.")
If (success <> True) Then
    Debug.WriteLine("Could not build text.")
    Exit Sub
End If

success = endpoint.Append(region)
If (success <> True) Then
    Debug.WriteLine("Could not build text.")
    Exit Sub
End If

success = endpoint.Append(".amazonaws.com")
If (success <> True) Then
    Debug.WriteLine("Could not build text.")
    Exit Sub
End If

Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
'  Connect to the SAME hostname used for TLS verification and request signing.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
    Debug.WriteLine("TLS connection failed; inspect diagnostics privately.")
    Exit Sub
End If

success = rest.UseConnection(connection,True)
If (success <> True) Then
    Debug.WriteLine("Could not attach the TLS connection.")
    Exit Sub
End If

Dim xml As New Chilkat.Xml
xml.Strict = True
rest.Host = endpoint.GetAsString()
If (credentials.HasMember("session_token") = True) Then
    If (credentials.JsonTypeOf("session_token") <> 1) Then
        Debug.WriteLine("session_token must be a string.")
        Exit Sub
    End If

End If

'  One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
Dim batch As New Chilkat.JsonObject
batch.Strict = True
success = batch.LoadFile("qa_data/aws/delete-objects.json")
If (success <> True) Then
    Debug.WriteLine("Could not load the intended deletion batch.")
    Exit Sub
End If

Dim count As Integer = batch.SizeOfArray("objects")
If ((count < 1) Or (count > 1000)) Then
    Debug.WriteLine("Supply 1 to 1000 objects in the batch.")
    Exit Sub
End If

xml.Tag = "Delete"
success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/")
If (success <> True) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If

xml.UpdateChildContent("Quiet","false")
Dim requested As New Chilkat.Hashtable
Dim identity As New Chilkat.JsonObject
Dim i As Integer = 0
While (i < count)
    batch.I = i
    xml.I = i
    textCompare.Clear()
    textCompare.SetString(batch.StringOf("objects[i].key"))
    Dim sameText3 As Boolean = textCompare.ContentsEqual("",True)
    If ((batch.JsonTypeOf("objects[i].key") <> 1) Or (sameText3 = True)) Then
        Debug.WriteLine("Each object needs a nonempty key.")
        Exit Sub
    End If

    Dim key As String = batch.StringOf("objects[i].key")
    Dim version As String = ""
    If (batch.HasMember("objects[i].version_id") = True) Then
        textCompare.Clear()
        textCompare.SetString(batch.StringOf("objects[i].version_id"))
        Dim sameText4 As Boolean = textCompare.ContentsEqual("",True)
        If ((batch.JsonTypeOf("objects[i].version_id") <> 1) Or (sameText4 = True)) Then
            Debug.WriteLine("version_id must be a nonempty string when present.")
            Exit Sub
        End If

        version = batch.StringOf("objects[i].version_id")
        xml.UpdateChildContent("Object[i]|VersionId",version)
    End If

    xml.UpdateChildContent("Object[i]|Key",key)
    success = identity.UpdateString("key",key)
    If (success <> True) Then
        Debug.WriteLine("Could not build saved state.")
        Exit Sub
    End If

    success = identity.UpdateString("version",version)
    If (success <> True) Then
        Debug.WriteLine("Could not build saved state.")
        Exit Sub
    End If

    Dim requestIdentity As String = identity.Emit()
    If (requested.Contains(requestIdentity) = True) Then
        Debug.WriteLine("Duplicate key/version in deletion batch.")
        Exit Sub
    End If

    success = requested.AddInt(requestIdentity,1)
    If (success <> True) Then
        Debug.WriteLine("Could not prepare the request.")
        Exit Sub
    End If

    i = i + 1
End While
Dim requestBody As String = 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.
Dim host As New Chilkat.StringBuilder
host.Append(endpoint.GetAsString())
Dim now As New Chilkat.CkDateTime
success = now.SetFromCurrentSystemTime()
If (success <> True) Then
    Debug.WriteLine("Could not read system time.")
    Exit Sub
End If

Dim timestamp As New Chilkat.StringBuilder
timestamp.Append(now.GetAsTimestamp(False))
Dim removedDashes As Integer = timestamp.Replace("-","")
Dim removedColons As Integer = timestamp.Replace(":","")
Dim amzDate As String = timestamp.GetAsString()
Dim dateStamp As String = timestamp.GetRange(0,8,False)
Dim crypt As New Chilkat.Crypt2
crypt.Charset = "utf-8"
crypt.HashAlgorithm = "md5"
crypt.EncodingMode = "base64"
Dim contentMd5 As String = crypt.HashStringENC(requestBody)
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not hash delete body.")
    Exit Sub
End If

crypt.HashAlgorithm = "sha256"
crypt.EncodingMode = "hexlower"
Dim payloadHash As String = crypt.HashStringENC(requestBody)
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not hash delete body.")
    Exit Sub
End If

Dim signedHeaders As New Chilkat.StringBuilder
signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date")
Dim canonical As New Chilkat.StringBuilder
canonical.Append("POST" & vbLf & "/" & vbLf & "delete=" & vbLf & "content-md5:")
canonical.Append(contentMd5)
canonical.Append(vbLf & "host:")
canonical.Append(host.GetAsString())
canonical.Append(vbLf & "x-amz-content-sha256:")
canonical.Append(payloadHash)
canonical.Append(vbLf & "x-amz-date:")
canonical.Append(amzDate)
canonical.Append(vbLf)
If (credentials.HasMember("session_token") = True) Then
    textCompare.Clear()
    textCompare.SetString(credentials.StringOf("session_token"))
    Dim sameText5 As Boolean = textCompare.ContentsEqual("",True)
    If (sameText5 <> True) Then
        signedHeaders.Append(";x-amz-security-token")
        canonical.Append("x-amz-security-token:")
        canonical.Append(credentials.StringOf("session_token"))
        canonical.Append(vbLf)
        success = rest.AddHeader("x-amz-security-token",credentials.StringOf("session_token"))
        If (success <> True) Then
            Debug.WriteLine("Could not prepare the request.")
            Exit Sub
        End If

    End If

End If

canonical.Append(vbLf)
canonical.Append(signedHeaders.GetAsString())
canonical.Append(vbLf)
canonical.Append(payloadHash)
Dim canonicalHash As String = crypt.HashStringENC(canonical.GetAsString())
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not hash canonical request.")
    Exit Sub
End If

Dim scope As New Chilkat.StringBuilder
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
Dim stringToSign As New Chilkat.StringBuilder
stringToSign.Append("AWS4-HMAC-SHA256" & vbLf)
stringToSign.Append(amzDate)
stringToSign.Append(vbLf)
stringToSign.Append(scope.GetAsString())
stringToSign.Append(vbLf)
stringToSign.Append(canonicalHash)
Dim initialKey As New Chilkat.StringBuilder
initialKey.Append("AWS4")
initialKey.Append(credentials.StringOf("secret_key"))
crypt.MacAlgorithm = "hmac"
success = crypt.SetMacKeyString(initialKey.GetAsString())
If (success <> True) Then
    Debug.WriteLine("Could not set signing key.")
    Exit Sub
End If

Dim derivedKey As String = crypt.MacStringENC(dateStamp)
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not derive date signing key.")
    Exit Sub
End If

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> True) Then
    Debug.WriteLine("Could not set derived signing key.")
    Exit Sub
End If

derivedKey = crypt.MacStringENC(region)
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not derive signing key.")
    Exit Sub
End If

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> True) Then
    Debug.WriteLine("Could not set derived signing key.")
    Exit Sub
End If

derivedKey = crypt.MacStringENC("s3")
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not derive signing key.")
    Exit Sub
End If

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> True) Then
    Debug.WriteLine("Could not set derived signing key.")
    Exit Sub
End If

derivedKey = crypt.MacStringENC("aws4_request")
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not derive signing key.")
    Exit Sub
End If

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> True) Then
    Debug.WriteLine("Could not set final signing key.")
    Exit Sub
End If

Dim signature As String = crypt.MacStringENC(stringToSign.GetAsString())
If (crypt.LastMethodSuccess <> True) Then
    Debug.WriteLine("Could not sign delete request.")
    Exit Sub
End If

Dim authorization As 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) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If


success = rest.AddHeader("Content-MD5",contentMd5)
If (success <> True) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If


success = rest.AddHeader("x-amz-content-sha256",payloadHash)
If (success <> True) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If


success = rest.AddHeader("x-amz-date",amzDate)
If (success <> True) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If


success = rest.AddQueryParam("delete","")
If (success <> True) Then
    Debug.WriteLine("Could not prepare the request.")
    Exit Sub
End If

Dim responseBody As String = rest.FullRequestString("POST","/",requestBody)
If (rest.LastMethodSuccess <> True) Then
    Debug.WriteLine("Request did not complete; inspect diagnostics privately.")
    Exit Sub
End If

If (rest.ResponseStatusCode <> 200) Then
    Debug.WriteLine("S3 HTTP status: " & rest.ResponseStatusCode)
    success = xml.LoadXml(responseBody)
    textCompare.Clear()
    textCompare.SetString(xml.Tag)
    Dim sameText6 As Boolean = textCompare.ContentsEqual("Error",True)
    If ((success = True) And (sameText6 = True)) Then
        Debug.WriteLine("S3 error code: " & xml.GetChildContent("Code"))
    End If

    '  Keep signed headers, credentials, URLs, and full diagnostics private.
    '  A timeout may leave a write's outcome uncertain. Check before retrying.
    Exit Sub
End If

success = xml.LoadXml(responseBody)
If (success <> True) Then
    Debug.WriteLine("Expected well-formed XML.")
    Exit Sub
End If

textCompare.Clear()
textCompare.SetString(xml.Tag)
Dim sameText7 As Boolean = textCompare.ContentsEqual("DeleteResult",True)
If (sameText7 <> True) Then
    Debug.WriteLine("Unexpected S3 response element; this is not a successful result.")
    Exit Sub
End If

Dim deleted As Integer = xml.NumChildrenHavingTag("Deleted")
Dim failed As Integer = xml.NumChildrenHavingTag("Error")
If (deleted + failed <> count) Then
    Debug.WriteLine("Incomplete result: reconcile every requested object before retrying.")
    Exit Sub
End If

Dim received As New Chilkat.Hashtable
Dim resultType As Integer = 0
While (resultType < 2)
    Dim itemTag As String = "Deleted"
    Dim resultCount As Integer = deleted
    If (resultType = 1) Then
        itemTag = "Error"
        resultCount = failed
    End If

    Dim j As Integer = 0
    While (j < resultCount)
        xml.I = j
        Dim itemPath As New Chilkat.StringBuilder
        success = itemPath.Append(itemTag)
        If (success <> True) Then
            Debug.WriteLine("Could not build text.")
            Exit Sub
        End If

        success = itemPath.Append("[i]")
        If (success <> True) Then
            Debug.WriteLine("Could not build text.")
            Exit Sub
        End If

        Dim item As Chilkat.Xml = xml.FindChild(itemPath.GetAsString())
        If (xml.LastMethodSuccess <> True) Then
            Debug.WriteLine("Missing deletion result entry.")
            Exit Sub
        End If

        Dim resultKey As String = item.GetChildContent("Key")
        Dim resultVersion As String = ""
        If (item.HasChildWithTag("VersionId") = True) Then
            resultVersion = item.GetChildContent("VersionId")
        End If

        success = identity.UpdateString("key",resultKey)
        If (success <> True) Then
            Debug.WriteLine("Could not build saved state.")
            Exit Sub
        End If

        success = identity.UpdateString("version",resultVersion)
        If (success <> True) Then
            Debug.WriteLine("Could not build saved state.")
            Exit Sub
        End If

        Dim responseIdentity As String = identity.Emit()
        If ((requested.Contains(responseIdentity) <> True) Or (received.Contains(responseIdentity) = True)) Then
            Debug.WriteLine("Unexpected or duplicated deletion result; reconcile manually.")
            Exit Sub
        End If

        success = received.AddInt(responseIdentity,1)
        If (success <> True) Then
            Debug.WriteLine("Could not prepare the request.")
            Exit Sub
        End If

        Debug.WriteLine(itemTag & ": " & resultKey)
        If (resultType = 1) Then
            Debug.WriteLine("Error code: " & item.GetChildContent("Code"))
        End If


        j = j + 1
    End While
    resultType = resultType + 1
End While
If (failed > 0) Then
    Debug.WriteLine("Batch has per-object failures. Do not retry successful entries.")
    Exit Sub
End If

Debug.WriteLine("All requested deletions acknowledged.")