问题
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