8

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

对于读取和写入文件,我们有以下成员:

Stream OpenRead();
Stream OpenWrite();

我们的应用程序的一部分将文档“捆绑”到一个文件中。对于我们的本地存储提供者OpenWrite返回一个可附加的流:

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

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

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

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

4

2 回答 2

6

基于OpenWrite此处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.

您可以做的一件事是读取流中的 blob 数据并将该流返回到调用应用程序,然后让该应用程序将数据附加到该流。例如,请参见下面的代码:

    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;
                }
            }
        }
    }
于 2013-10-03T15:27:42.593 回答
3

现在有一个CloudAppendBlob类允许您向现有 blob 添加内容:

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

在您的情况下,您想从流中追加:

await blob.AppendFromStreamAsync(new MemoryStream());

但是您可以从文本、字节数组、文件中追加。检查文档。

于 2017-12-11T05:39:04.480 回答