Kzryzstof
Kzryzstof

Reputation: 8382

How can I open a writeable stream to a new Blob using the new Azure Storage SDK v12?

I am using Azure Storage SDK v12 and I am looking for a way to open a stream to specific Blob, like in the previous versions:

CloudBlobClient cloudBlobClient = account.CreateCloudBlobClient();

CloudBlobContainer container = cloudBlobClient.GetContainerReference("zipfiles");

var blob = container.GetBlockBlobReference(Guid.NewGuid().ToString());

// Here is the the functionality I am looking for: OpenWrite that returns a Stream.
using (Stream blobStream = blob.OpenWrite())
{
  ....
}

The problem is that I do not find the OpenWrite method in the new API that would get me access to a Stream.

Question

How can I open a writeable stream to a Blob using the new Azure Storage SDK v12?


Workaround

Since I am working with Azure Functions, I have a workaround that involves using the Blob as Out parameter of my function:

public async Task RunAsync(
            [BlobTrigger("data/{listId}/{name}.txt", Connection = "storageAccountConnectionString")]
            Stream sourceStream,
            string listId,
            string name,
            [Blob("data/{listId}/processed/{name}.txt", FileAccess.Write, Connection = "storageAccountConnectionString")] 
            Stream destinationStream)
{
    //  Here I use the destinationStream instance to upload data as it is being processed. It prevents me from loading everything in memory before calling the UploadAsync method of a BlobClient instance.
}

Upvotes: 9

Views: 10791

Answers (2)

PavLes
PavLes

Reputation: 191

You need to use GetBlockBlobClient extension method from the Azure.Storage.Blobs.Specialized namespace:

public async Task<Stream> CreateOutputStream(string fullFilePath)
{
    var blockBlobClient = _blobContainerClient.GetBlockBlobClient(fullFilePath);
    var stream = await blockBlobClient.OpenWriteAsync(true);

    return stream;
}

Upvotes: 19

Vova Bilyachat
Vova Bilyachat

Reputation: 19484

Try this

BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync("zipfiles");
BlobClient blobClient = containerClient.GetBlobClient(Guid.NewGuid().ToString());

using(FileStream strem = File.OpenRead("10_million_lines.file")){
   await blobClient.UploadAsync(strem , true);
}

Upvotes: 2

Related Questions