我们有一个文件系统抽象,允许我们在本地和云(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内容。是否可以返回可附加到?
的可写流答案 0 :(得分:5)
基于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;
}
}
}
}
答案 1 :(得分:0)
现在有一个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());
但是您可以从文本,字节数组,文件追加。查看文档。