Can PutBlock be used to append to an existing BlockBlob in Azure

荒凉一梦 提交于 2021-01-21 11:32:27

问题


As per the title, I have a program whereby I'm trying to add to an existing BlobkBlob using the PutBlock method:

    private static void UploadNewText(string text)
    {
        string fileName = "test4.txt";
        string containerString = "mycontainer";

        CloudStorageAccount storage = CloudStorageAccount.Parse(connection);
        CloudBlobClient client = storage.CreateCloudBlobClient();
        CloudBlobContainer container = client.GetContainerReference(containerString);
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

        using (MemoryStream stream = new MemoryStream())
        using (StreamWriter sw = new StreamWriter(stream))
        {
            sw.Write(text);
            sw.Flush();
            stream.Position = 0;

            string blockId = Convert.ToBase64String(
                ASCIIEncoding.ASCII.GetBytes("0000005"));

            Console.WriteLine(blockId);

            blob.PutBlock(blockId, stream, null);
            blob.PutBlockList(new string[] { blockId });
        }
    }

As I understand it, providing the BlockId increases (or at least differs), and is a consistent size, this should work; however, when I run it a second time for the same file (regardless of whether or not I increase the Block ID) it just overwrites the existing file with the new text.

I realise there are other options for appending to a blob (such as AppendBlob), but I'm curious if PutBlock, specifically can do this. Is what I am trying to do possible and, if so, what am I doing wrong?


回答1:


Can PutBlock be used to append to an existing BlockBlob in Azure

Yes, it can. However in order to do that, you will need to work that in a little bit different way.

What you will need to do is:

  1. First get the previously committed block list. The method you want to use is DownloadBlockList.
  2. Upload new block. Note down its block id.
  3. Append this block id to the list of block ids you downloaded in step #1.
  4. Call put block list with this new list.


来源:https://stackoverflow.com/questions/46368954/can-putblock-be-used-to-append-to-an-existing-blockblob-in-azure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!