Azure Blob: Resume a Download with ETag Protection
See more Azure Cloud Storage Examples
Save the account, path, ETag and size in an immutable checkpoint, then append complete byte ranges to a private .part file. A later run uses the existing partial-file length as its offset and checks that HEAD still describes the same blob. Every range carries If-Match and must return the expected ETag, exact Content-Range, Content-Length and body size before any bytes are appended.
The demonstration bounds offsets to 2,000,000,000 bytes so it can use int arithmetic without overflow; this is not an Azure service limit. Sizes in checkpoints remain strings. Only the final successful transfer renames the partial output to the final filename. Empty blobs are handled without issuing an invalid range.
Use one process, an exclusive local destination and an unchanged partial file. The checkpoint does not independently hash or authenticate local content; do not point it at an unrelated file or reuse a partial file that was edited or suffered disk corruption. After a local write failure inspect or restart the partial file. On 412 or changed HEAD properties, preserve the previous partial output and start a new download separately instead of combining versions. A crash while initially publishing the checkpoint fails closed if state is incomplete.
Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.
Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkRestW.h>
#include <CkAuthAzureStorageW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
#include <CkBinDataW.h>
void ChilkatSample(void)
{
bool success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilderW textCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
CkJsonObjectW config;
config.put_Strict(true);
success = config.LoadFile(L"qa_data/azure/storage.json");
if (success != true) {
wprintf(L"Could not load private Azure configuration.\n");
return;
}
textCompare.Clear();
textCompare.SetString(config.stringOf(L"account"));
bool sameText1 = textCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"account") != 1) || (sameText1 == true)) {
wprintf(L"Supply the storage account name.\n");
return;
}
// access_key is the base64 account key, not a connection string or SAS.
textCompare.Clear();
textCompare.SetString(config.stringOf(L"access_key"));
bool sameText2 = textCompare.ContentsEqual(L"",true);
if ((config.JsonTypeOf(L"access_key") != 1) || (sameText2 == true)) {
wprintf(L"Supply the base64 account access key.\n");
return;
}
CkStringBuilderW endpoint;
success = endpoint.Append(config.stringOf(L"account"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = endpoint.Append(L".blob.core.windows.net");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// resourcePath is already URL-encoded. Encode each path segment once when adapting it.
// Keep slash separators; names and paths are case-sensitive.
const wchar_t *resourcePath = L"/examplecontainer/example.bin";
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
CkAuthAzureStorageW azAuth;
azAuth.put_Account(config.stringOf(L"account"));
azAuth.put_AccessKey(config.stringOf(L"access_key"));
azAuth.put_Service(L"Blob");
azAuth.put_Scheme(L"SharedKey");
azAuth.put_XMsVersion(L"2026-04-06");
success = rest.SetAuthAzureStorage(azAuth);
if (success != true) {
wprintf(L"Could not configure Shared Key signing.\n");
return;
}
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
// Do not replay a write automatically after losing its response.
success = rest.UseConnection(connection,false);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
const wchar_t *responseText = 0;
CkXmlW result;
result.put_Strict(true);
const wchar_t *partFile = L"qa_output/resume.bin.part";
const wchar_t *finalFile = L"qa_output/resume.bin";
const wchar_t *checkpointFile = L"qa_data/azure/download-checkpoint.json";
CkFileAccessW files;
if (files.FileExists(finalFile) == true) {
wprintf(L"Choose a new final filename; existing output is preserved.\n");
return;
}
responseText = rest.fullRequestNoBody(L"HEAD",resourcePath);
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"Request did not complete; outcome may be uncertain.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"HTTP status: %d\n",rest.get_ResponseStatusCode());
wprintf(L"Azure error code: %s\n",rest.responseHdrByName(L"x-ms-error-code"));
wprintf(L"Request ID: %s\n",rest.responseHdrByName(L"x-ms-request-id"));
// Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return;
}
const wchar_t *etag = rest.responseHdrByName(L"ETag");
textCompare.Clear();
textCompare.SetString(etag);
bool sameText3 = textCompare.ContentsEqual(L"",true);
if (sameText3 == true) {
wprintf(L"Missing blob ETag.\n");
return;
}
const wchar_t *totalText = rest.responseHdrByName(L"Content-Length");
CkStringBuilderW totalValue;
success = totalValue.Append(totalText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
if ((totalValue.get_Length() < 1) || (totalValue.get_Length() > 10)) {
wprintf(L"Invalid or oversized length for this bounded example.\n");
return;
}
CkStringBuilderW totalDigits;
success = totalDigits.Append(totalText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int totalRemoved = 0;
totalRemoved = totalDigits.Replace(L"0",L"");
totalRemoved = totalDigits.Replace(L"1",L"");
totalRemoved = totalDigits.Replace(L"2",L"");
totalRemoved = totalDigits.Replace(L"3",L"");
totalRemoved = totalDigits.Replace(L"4",L"");
totalRemoved = totalDigits.Replace(L"5",L"");
totalRemoved = totalDigits.Replace(L"6",L"");
totalRemoved = totalDigits.Replace(L"7",L"");
totalRemoved = totalDigits.Replace(L"8",L"");
totalRemoved = totalDigits.Replace(L"9",L"");
if (totalDigits.get_Length() != 0) {
wprintf(L"Length must be a decimal string.\n");
return;
}
if ((totalValue.get_Length() == 10) && (totalValue.StartsWith(L"1",true) != true) && (totalValue.ContentsEqual(L"2000000000",true) != true)) {
wprintf(L"Length exceeds the 2,000,000,000-byte demonstration bound.\n");
return;
}
CkJsonObjectW totalNumber;
success = totalNumber.UpdateNumber(L"value",totalText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int total = totalNumber.IntOf(L"value");
CkJsonObjectW checkpoint;
checkpoint.put_Strict(true);
if (files.FileExists(checkpointFile) == true) {
success = checkpoint.LoadFile(checkpointFile);
if (success != true) {
wprintf(L"Invalid checkpoint.\n");
return;
}
textCompare.Clear();
textCompare.SetString(checkpoint.stringOf(L"path"));
bool sameText4 = textCompare.ContentsEqual(resourcePath,true);
textCompare.Clear();
textCompare.SetString(checkpoint.stringOf(L"etag"));
bool sameText5 = textCompare.ContentsEqual(etag,true);
textCompare.Clear();
textCompare.SetString(checkpoint.stringOf(L"size"));
bool sameText6 = textCompare.ContentsEqual(totalText,true);
if ((checkpoint.stringOf(L"account") != config.stringOf(L"account")) || (sameText4 != true) || (sameText5 != true) || (sameText6 != true)) {
wprintf(L"The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.\n");
return;
}
}
else {
if (files.FileExists(partFile) == true) {
wprintf(L"Partial file exists without its checkpoint; refusing to append.\n");
return;
}
success = checkpoint.UpdateString(L"account",config.stringOf(L"account"));
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"path",resourcePath);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"etag",etag);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.UpdateString(L"size",totalText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = checkpoint.WriteFile(L"qa_data/azure/download-checkpoint.tmp");
if (success != true) {
wprintf(L"Could not write checkpoint.\n");
return;
}
success = files.FileRename(L"qa_data/azure/download-checkpoint.tmp",checkpointFile);
if (success != true) {
wprintf(L"Could not publish checkpoint.\n");
return;
}
}
// The immutable checkpoint identifies the version. Actual local length is the resume offset.
// Keep this partial file private, unchanged and exclusive to this one download.
const wchar_t *localSize = L"0";
if (files.FileExists(partFile) == true) {
localSize = files.fileSizeStr(partFile);
if (files.get_LastMethodSuccess() != true) {
wprintf(L"Could not get partial-file size.\n");
return;
}
}
const wchar_t *offsetText = localSize;
CkStringBuilderW offsetValue;
success = offsetValue.Append(offsetText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
if ((offsetValue.get_Length() < 1) || (offsetValue.get_Length() > 10)) {
wprintf(L"Invalid or oversized length for this bounded example.\n");
return;
}
CkStringBuilderW offsetDigits;
success = offsetDigits.Append(offsetText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int offsetRemoved = 0;
offsetRemoved = offsetDigits.Replace(L"0",L"");
offsetRemoved = offsetDigits.Replace(L"1",L"");
offsetRemoved = offsetDigits.Replace(L"2",L"");
offsetRemoved = offsetDigits.Replace(L"3",L"");
offsetRemoved = offsetDigits.Replace(L"4",L"");
offsetRemoved = offsetDigits.Replace(L"5",L"");
offsetRemoved = offsetDigits.Replace(L"6",L"");
offsetRemoved = offsetDigits.Replace(L"7",L"");
offsetRemoved = offsetDigits.Replace(L"8",L"");
offsetRemoved = offsetDigits.Replace(L"9",L"");
if (offsetDigits.get_Length() != 0) {
wprintf(L"Length must be a decimal string.\n");
return;
}
if ((offsetValue.get_Length() == 10) && (offsetValue.StartsWith(L"1",true) != true) && (offsetValue.ContentsEqual(L"2000000000",true) != true)) {
wprintf(L"Length exceeds the 2,000,000,000-byte demonstration bound.\n");
return;
}
CkJsonObjectW offsetNumber;
success = offsetNumber.UpdateNumber(L"value",offsetText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int offset = offsetNumber.IntOf(L"value");
if (offset > total) {
wprintf(L"Partial file is longer than the selected blob.\n");
return;
}
// Ensure an empty blob also creates a local file.
success = files.OpenForAppend(partFile);
if (success != true) {
wprintf(L"Could not open partial file.\n");
return;
}
files.FileClose();
success = rest.AddHeader(L"If-Match",etag);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
CkBinDataW chunk;
CkStringBuilderW range;
CkStringBuilderW expectedRange;
CkStringBuilderW expectedLength;
while ((offset < total)) {
int count = total - offset;
if (count > 4194304) {
count = 4194304;
}
int endByte = offset + count - 1;
range.Clear();
success = range.Append(L"bytes=");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = range.AppendInt(offset);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = range.Append(L"-");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = range.AppendInt(endByte);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.AddHeader(L"x-ms-range",range.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
expectedRange.Clear();
success = expectedRange.Append(L"bytes ");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedRange.AppendInt(offset);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedRange.Append(L"-");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedRange.AppendInt(endByte);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedRange.Append(L"/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedRange.Append(totalText);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
expectedLength.Clear();
success = expectedLength.AppendInt(count);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
rest.Disconnect(10);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS reconnection failed.\n");
return;
}
success = rest.UseConnection(connection,false);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.SendReqNoBody(L"GET",resourcePath);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
int httpStatus = rest.ReadResponseHeader();
if (httpStatus < 0) {
wprintf(L"Could not read range response headers.\n");
return;
}
if (rest.get_ResponseStatusCode() != 206) {
wprintf(L"HTTP status: %d\n",rest.get_ResponseStatusCode());
wprintf(L"Azure error code: %s\n",rest.responseHdrByName(L"x-ms-error-code"));
wprintf(L"Request ID: %s\n",rest.responseHdrByName(L"x-ms-request-id"));
// Inspect any error body privately; do not log credentials, SAS URLs or payloads.
return;
}
textCompare.Clear();
textCompare.SetString(rest.responseHdrByName(L"ETag"));
bool sameText7 = textCompare.ContentsEqual(etag,true);
if ((sameText7 != true) || (rest.responseHdrByName(L"Content-Range") != expectedRange.getAsString()) || (rest.responseHdrByName(L"Content-Length") != expectedLength.getAsString())) {
wprintf(L"Unexpected range response; no bytes appended.\n");
return;
}
success = chunk.Clear();
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = rest.ReadRespBd(chunk);
if (success != true) {
wprintf(L"Incomplete range body; no bytes appended.\n");
return;
}
if (chunk.get_NumBytes() != count) {
wprintf(L"Wrong byte count; no bytes appended.\n");
return;
}
success = files.OpenForAppend(partFile);
if (success != true) {
wprintf(L"Could not reopen partial file.\n");
return;
}
success = files.FileWriteBd(chunk,0,0);
files.FileClose();
if (success != true) {
wprintf(L"Local write failed. Inspect the partial file before retrying.\n");
return;
}
offset = offset + count;
}
success = files.FileRename(partFile,finalFile);
if (success != true) {
wprintf(L"Could not publish completed download.\n");
return;
}
wprintf(L"Download complete. Retain or archive the checkpoint with the completed file.\n");
}