Redaguoti

Bendrinti naudojant


Append data to an append blob with .NET

You can append data to a blob by creating an append blob. Append blobs are made up of blocks like block blobs, but are optimized for append operations. Append blobs are ideal for scenarios such as logging data from virtual machines.

Note

The examples in this article assume that you've created a BlobServiceClient object by using the guidance in the Get started with Azure Blob Storage and .NET article. Blobs in Azure Storage are organized into containers. Before you can upload a blob, you must first create a container. To learn how to create a container, see Create a container in Azure Storage with .NET.

Create an append blob and append data

Use these methods to create an append blob.

Use either of these methods to append data to that append blob:

The maximum size in bytes of each append operation is defined by the AppendBlobMaxAppendBlockBytes property. The following example creates an append blob and appends log data to that blob. This example uses the AppendBlobMaxAppendBlockBytes property to determine whether multiple append operations are required.

static async Task AppendToBlob(
    BlobContainerClient containerClient,
    MemoryStream logEntryStream,
    string logBlobName)
{
    AppendBlobClient appendBlobClient = containerClient.GetAppendBlobClient(logBlobName);

    await appendBlobClient.CreateIfNotExistsAsync();

    int maxBlockSize = appendBlobClient.AppendBlobMaxAppendBlockBytes;
    long bytesLeft = logEntryStream.Length;
    byte[] buffer = new byte[maxBlockSize];
    while (bytesLeft > 0)
    {
        int blockSize = (int)Math.Min(bytesLeft, maxBlockSize);
        int bytesRead = await logEntryStream.ReadAsync(buffer.AsMemory(0, blockSize));
        await using (MemoryStream memoryStream = new MemoryStream(buffer, 0, bytesRead))
        {
            await appendBlobClient.AppendBlockAsync(memoryStream);
        }
        bytesLeft -= bytesRead;
    }
}

See also