Search code examples
c#azure-storageazure-blob-storage

How to check if Azure Blob file Exists or Not


I want to check a particular file exist in Azure Blob Storage. Is it possible to check by specifying it's file name? Each time i got File Not Found Error.


Solution

  • This extension method should help you:

    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;
                }
            }
        }
    }
    

    Usage:

    static void Main(string[] args)
    {
        var blob = CloudStorageAccount.DevelopmentStorageAccount
            .CreateCloudBlobClient().GetBlobReference(args[0]);
        // or CloudStorageAccount.Parse("<your connection string>")
    
        if (blob.Exists())
        {
            Console.WriteLine("The blob exists!");
        }
        else
        {
            Console.WriteLine("The blob doesn't exist.");
        }
    }
    

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