How to validate if Blob is exists or not in deleted list

删除回忆录丶 提交于 2020-01-15 04:01:41

问题


Following code will able to see if blob exists or not.

var blob = client.GetContainerReference(containerName).GetBlockBlobReference(blobFileName);

if (blob.Exists())

How to validate if blob is exists or not in deleted list as well ?


回答1:


Great question! So if a blob is deleted and if you check for its existence by calling Exists() method, it will always tell you that blob does not exist. You will get a 404 (NotFound) error if you try to fetch the attributes.

However you can still find out if the blob is in deleted state but for that you would need to list blobs in the container. Since a blob container can possibly contains thousands of blobs, to reduce multiple calls to the storage service, you should list blobs names of which start with the name of the blob.

Here's the sample code:

    static void CheckForDeletedBlob()
    {
        var containerName = "container-name";
        var blobName = "blob-name";
        var storageCredetials = new StorageCredentials(accountName, accountKey);
        var storageAccount = new CloudStorageAccount(storageCredetials, true);
        var blobClient = storageAccount.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference(containerName);
        var blob = container.GetBlockBlobReference(blobName);
        var exists = blob.Exists();
        if (!exists)
        {
            var blobs = container.ListBlobs(prefix: blob.Name, useFlatBlobListing: true, blobListingDetails: BlobListingDetails.Deleted).ToList();
            if (blobs.FirstOrDefault(b => b.Uri.AbsoluteUri == blob.Uri.AbsoluteUri) == null)
            {
                Console.WriteLine("Blob does not exist!");
            }
            else
            {
                Console.WriteLine("Blob exists but is in deleted state.");
            }
        }
        else
        {
            Console.WriteLine("Blob does not exist!");
        }
    }



回答2:


You could use blob.Exists() to validate if blob exists or not, then use container.ListBlobs(useFlatBlobListing: true, blobListingDetails: BlobListingDetails.Deleted) to list all the blobs including deleted blobs(all soft deleted and active blobs in a container), validate the blob if exist in the collection.



来源:https://stackoverflow.com/questions/52613916/how-to-validate-if-blob-is-exists-or-not-in-deleted-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!