[Windows Azure]檢查Blob是否存在的方法

  • 1293
  • 0

摘要:[Windows Azure]檢查Blob是否存在的方法

這個大概是我一年前從網路上發現的,過了一年SDK也更新了好幾個版本,

假如有更新更好的方法,還請各位高手提示。

 

當初在撰寫與Blob相關的程式時,都是使用Microsoft.WindowsAzure.StorageClient命名空間的類別來開發,

但卻發現沒有一個好的方法來檢查Blob是否存在(被微軟寵慣了...),因此在網路上找到這個小技巧:

public static class BlobExtensions
{
    public static bool Exists(this CloudBlob blob)
    {
        try
        {
            blob.FetchAttributes();
            return true;
        }
        catch (StorageClientException e)
        {
            if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
            {
                return false;
            }
            else
            {
                throw;
            }
        }
    }
}

FetchAttributes()這個動作是用來擷取Blob的中繼資料(Metadata),假如該Blob不存在,

則會拋出一個StorageClientException例外,並判斷ErrorCode是否為StorageErrorCode.ResourceNotFound,

來確定該Blob不存在。

 

參考資料:

http://blog.smarx.com/posts/testing-existence-of-a-windows-azure-blob