Search code examples
azureazure-storageazure-blob-storage

Deleting Blob from Azure storage using C#


The package which I am using is Azure.Storage.Blobs (v12.9.1) and I am trying to delete a blob.

Here is the code I have written (I do not get any errors):

//path - storage url without token 
public async Task<bool> DeleteFilefromStorage(string path)
{
        try
        {
            BlobServiceClient blobServiceClient = new BlobServiceClient(Helper.StorageCS);

            string containerName = Helper.ContainerName;

            Uri uri = new Uri(path);
            string filename = Path.GetFileName(uri.LocalPath);

            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);

            var blob = blobContainerClient.GetBlobClient(filename);

            return await blob.DeleteIfExistsAsync();
        }
        catch
        {
            throw;
        }
    }

Solution

  • The reason your code is failing is because your blob URL is something like https://mystorage.blob.core.windows.net/mycontainer/files/ba143f66-ba18-478a-85d6-0d661e6894dd.xlsx where the file (ba143f66-ba18-478a-85d6-0d661e6894dd.xlsx) is inside a virtual folder called files.

    However when you do string filename = Path.GetFileName(uri.LocalPath);, it will only return ba143f66-ba18-478a-85d6-0d661e6894dd.xlsx and not files/ba143f66-ba18-478a-85d6-0d661e6894dd.xlsx.

    Because of this when you try to delete the file, you will get a 404 error. Since DeleteIfExistsAsync method will eat 404 (Not Found) error, you will not get any errors but at the same time the blob will not be deleted as well (because it does not exist).