Add to Stream CloudBlockBlob

We have a file system abstraction that makes it easy to switch between on-premises and cloud-based (Azure) storage.

For reading and writing files, we have the following elements:

Stream OpenRead(); Stream OpenWrite(); 

Part of our application β€œlinks” documents into a single file. For our local OpenWrite storage OpenWrite , an additional stream is returned:

 public Stream OpenWrite() { return new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, BufferSize, useAsync: true); } 

To store Azure memory, we do the following:

 public Stream OpenWrite() { return blob.OpenWrite(); } 

Unfortunately, this overrides the contents of the blob each time. Is it possible to return a writable stream that can be added to?

+6
source share
2 answers

Based on the documentation for OpenWrite here http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.blob.cloudblockblob.openwrite.aspx , The OpenWrite method will overwrite an existing blob unless explicitly prevented using the accessCondition parameter.

One thing you can do is read the blob data in the stream and return that stream to the calling application and let this application add data to this stream. For example, see the code below:

  static void BlobStreamTest() { storageAccount = CloudStorageAccount.DevelopmentStorageAccount; CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("temp"); container.CreateIfNotExists(); CloudBlockBlob blob = container.GetBlockBlobReference("test.txt"); blob.UploadFromStream(new MemoryStream());//Let just create an empty blob for the sake of demonstration. for (int i = 0; i < 10; i++) { try { using (MemoryStream ms = new MemoryStream()) { blob.DownloadToStream(ms);//Read blob data in a stream. byte[] dataToWrite = Encoding.UTF8.GetBytes("This is line # " + (i + 1) + "\r\n"); ms.Write(dataToWrite, 0, dataToWrite.Length); ms.Position = 0; blob.UploadFromStream(ms); } } catch (StorageException excep) { if (excep.RequestInformation.HttpStatusCode != 404) { throw; } } } } 
+5
source

Now there is a CloudAppendBlob class that allows you to add content to an existing blob:

 var account = CloudStorageAccount.Parse("storage account connectionstring"); var client = account.CreateCloudBlobClient(); var container = client.GetContainerReference("container name"); var blob = container.GetAppendBlobReference("blob name"); 

In your case, you want to add from the stream:

 await blob.AppendFromStreamAsync(new MemoryStream()); 

But you can add from a text, byte array, file. Check the documentation.

0
source

Source: https://habr.com/ru/post/955192/


All Articles