附加到CloudBlockBlob流 [英] Append to CloudBlockBlob stream

查看:336
本文介绍了附加到CloudBlockBlob流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个文件系统抽象,可让我们轻松地在本地存储和云(Azure)存储之间切换.

We have a file system abstraction that allows us to easily switch between local and cloud (Azure) storage.

为了读写文件,我们具有以下成员:

For reading and writing files we have the following members:

Stream OpenRead();
Stream OpenWrite();

我们的应用程序的一部分将文件捆绑"到一个文件中.对于我们的本地存储提供商,OpenWrite返回一个 appendable 流:

Part of our application "bundles" documents into one file. For our local storage provider OpenWrite returns an appendable stream:

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

对于Azure blob存储,我们执行以下操作:

For Azure blob storage we do the following:

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

不幸的是,这每次都会覆盖blob的内容.是否可以返回可追加的可写流?

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

推荐答案

基于OpenWrite的文档,此处您可以做的一件事是读取流中的Blob数据,并将该流返回给您的调用应用程序,然后让该应用程序将数据追加到该流中.例如,请参见下面的代码:

One thing you could do is read the blob data in a stream and return that stream to your calling application and let that application append data to that 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's 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;
                }
            }
        }
    }

这篇关于附加到CloudBlockBlob流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆