Search code examples
c#azureazure-blob-storageazure-storage

How can I replace CloudBlockBlob.OpenWriteAsync() in the Azure.Storage.Blobs v12 SDK?


We have been using the older package Microsoft.Azure.Storage.Blob, and now we are moving to a newer Azure.Storage.Blobs v12.13.1. And thus need to replace a number of older methods we used.

But the CloudBlockBlob.OpenWriteAsync() I cannot find a good replacement for, in the new SDK (they seem to promise some alternatives - but still none has been provided so far).

Any suggestions on how to replace this method with the new package?

Here is our original code:

    private readonly CloudBlobContainer _container;

    public async Task<(string, int)> StoreCsvCollectionAsZipAsync(string zipFileName, IEnumerable<(string, IEnumerable<string>)> csvCollection)
    {
        var blob = _container.GetBlockBlobReference(zipFileName);
        await blob.DeleteIfExistsAsync();
        var maxRowCount = 0;

        const int bufferCapacityLines = 100;
        var bufferLinesCount = 0;
        var rowsBuffer = new StringBuilder();

        await using (var uploadStream = await blob.OpenWriteAsync())
        {
            using (var zipArchive = new ZipArchive(uploadStream, ZipArchiveMode.Create))
            {
                foreach (var (tableName, csvRows) in csvCollection)
                {
                    var rowCount = 0;
                    var zipArchiveEntry = zipArchive.CreateEntry(tableName);
                    await using var innerFile = zipArchiveEntry.Open();
                    foreach (var csvRow in csvRows)
                    {
                       ...
                    }

                    if (rowsBuffer.Length > 0)
                    {
                        var finalBytes = Encoding.UTF8.GetBytes(rowsBuffer.ToString());
                        await innerFile.WriteAsync(finalBytes);

                        rowsBuffer.Clear();
                    }

                    if (maxRowCount < rowCount) maxRowCount = rowCount;
                }
            }
        }

        var uri = GetSharedAccessUri(zipFileName);

        return (uri?.ToString() ?? "", maxRowCount);
    }

As the data could be large enough we do need to keep it as a stream.


Solution

  • The solution seems to be very simple and like this:

    ...
       var blob= _container.GetBlobClient(zipFileName);
       await blob.DeleteIfExistsAsync();
       await using (var uploadStream = await blob.OpenWriteAsync(true))
                {
    ...