写入blob流 - 如何失败和清理?

时间:2018-03-08 17:01:13

标签: c# azure-storage

使用Azure存储,我使用流写入blob。我有一个像这样的方法:

    public async Task<BlobSteamContainer> GetBlobStreamAsync(string filename, string contentType = "text/csv")
    {
        var blob = container.GetBlockBlobReference($"{filename}--{Guid.NewGuid().ToString()}.csv");
        blob.Properties.ContentType = contentType;
        return new BlobSteamContainer(blob.Uri.ToString(), await blob.OpenWriteAsync());
    }

BlobStreamContainer只是一个简单的对象,所以我可以一起跟踪文件名和流:

public class BlobSteamContainer : IDisposable
{
    public CloudBlobStream Stream { get; private set; }
    public string Filename { get; private set; }

    public BlobSteamContainer(string filename, CloudBlobStream stream)
    {
        Stream = stream;
        Filename = filename;
    }

    public void Dispose()
    {
        Stream.Close();
        Stream?.Dispose();
    }
}

然后我用它来这样:

using (var blobStream = await GetBlobStreamAsync(filename))
using (var outputStream = new StreamWriter(blobStream.Stream))
using (var someInputStream = ...)
{
    try
    {
        outputStream.WriteLine("write some stuff...");
        //....processing
        if (someCondition) {
            throw new MyException("can't write the file");
        }
        //....more processing
        outputStream.Flush();
    }
    catch(MyException e)
    {
        // what to do here? I want to stop writing
        // and remove any trace of the file in azure
        throw; // let the higher ups handle this
    }
}

somecondition是我事先知道的事情(显然还有更多涉及处理输入流和写出来的事情)。如果一切都很好,那么这很好用。我的问题在于找出处理写入过程中抛出异常的最佳方法。

我尝试删除catch中的文件,如下所示:

 DeleteBlob(blobStream.Filename);

其中:

public void DeleteBlob(string filename)
{
    var blob = container.GetBlobReference(filename);
    blob.Delete();
}

但问题是该文件可能尚未创建,因此会抛出Microsoft.WindowsAzure.Storage.StorageException告诉我文件未找到(然后文件最终会被创建!)

那么最简单的处理方法是什么?

0 个答案:

没有答案