how to check if there is data in an azure block blob

2.3k Views Asked by At

I'm trying to find an more elegant way of checking to see if there is anything in the blob storage I've created.

I have a service that reads from blob storage. I basically need to be sure that when my service is restarted, it will check if there is anything in blob to read and process before running normally.

I can't seem to find a method that checks if the blockblob is empty. I came up with a way to do this, but I would like to know if there is a more elegant way of doing this:

here is my solution, just check if you were able to download anything. Sure it works..

public bool IsBlobEmpty()
{
    string text;
    using (var memoryStream = new MemoryStream())
    {
        blockBlob.DownloadToStream(memoryStream);
        text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
        if (text.Length > 0)
        {
            return false;
        }
    }
    return true;
}
2

There are 2 best solutions below

2
On

You can use the Azure Storage Blob APIs to get the metadata information of the blob and check for its size - https://msdn.microsoft.com/en-us/library/azure/dd179394.aspx

Response headers from the server contains a Content-Length property

x-ms-meta-Name: myblob.txt
x-ms-meta-DateUploaded: Sun, 23 Oct 2013 18:45:18 GMT
x-ms-blob-type: BlockBlob
x-ms-lease-status: unlocked
x-ms-lease-state: available
Content-Length: 11
Content-Type: text/plain; charset=UTF-8
Date: Sun, 23 Oct 2013 19:49:38 GMT
ETag: "0x8CAE97120C1FF22"
Accept-Ranges: bytes
x-ms-version: 2013-08-15
Last-Modified: Wed, 23 Oct 2013 19:49
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.
2
On

You want to check inside the container. The following code returns the names of the blobs inside the given container. You can tweak the way you want.

private readonly CloudBlobClient _blobClient;

public List<string> GetBlockBlobNames(string containerName, 
   string prefix = null)
{
    var names = new List<string>();

    var container = _blobClient.GetContainerReference(containerName.ToLower());

    if (container.Exists())
    {
        IEnumerable<IListBlobItem> collection = container.ListBlobs(prefix, true);

        // Loop over items within the container and output the length and URI.
        foreach (IListBlobItem item in collection)
        {
            if (item is CloudBlockBlob)
            {
                var blob = (CloudBlockBlob) item;

                names.Add(blob.Name);
            }
            else if (item is CloudPageBlob)
            {
                var pageBlob = (CloudPageBlob) item;
                names.Add(pageBlob.Name);
            }
            else if (item is CloudBlobDirectory)
            {
                var directory = (CloudBlobDirectory) item;
            }
        }
    }

    return names;
}