Azure Blob File is Detected Not Exist While It Actually Exists

angeline mary marchella 10 Reputation points
2024-08-08T06:29:26.3733333+00:00

I want to move a video file from Azure Blob Storage to Sharepoint directly using C#. The code below does not work because there is a problem when getting the blobStream. I have ensured that my containerName and blobName are correct. However, when I checked the existence of the blobClient using blobClient.ExistAsync(), it always returns false. Does anyone know why a blob file cannot be detected while it actually exists in the Azure Blob Storage? Thanks in advance.

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;

namespace ZoomRecordingHelper
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var clientId = "";
            var clientSecret = "";
            var tenantId = "";

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            GraphClient = new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task UploadFileToSharePoint(string siteId, string driveId, string fileName, Stream fileStream)
        {
            try
            {
                var uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/items/root:/{fileName}:/content";

                using (var httpClient = new HttpClient())
                {
                    var accessToken = await GetAccessTokenAsync();
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    using (var httpRequest = new HttpRequestMessage(HttpMethod.Put, uploadUrl))
                    {
                        httpRequest.Content = new StreamContent(fileStream);
                        httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        using (var response = await httpClient.SendAsync(httpRequest))
                        {
                            response.EnsureSuccessStatusCode();
                            Console.WriteLine("File uploaded successfully.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error uploading file: {ex.Message}");
            }
        }
        
       public async Task<Stream> GetBlobStreamAsync(string connectionString, string containerName, string blobName)
        {
            var blobServiceClient = new BlobServiceClient(connectionString); // my conn string : DefaultEndpointsProtocol=https;AccountName=databinuscampussolution;AccountKey=xxxxxxxx;EndpointSuffix=core.windows.net

            var containerClient = blobServiceClient.GetBlobContainerClient(containerName); // my containerName : bm5

            var blobClient = containerClient.GetBlobClient(blobName); // my blobName : zoom/recording/BBS/2024-8-7/93116161045.mp4

            var isExist = await blobClient.ExistsAsync(); //always return false

        if (isExist.Value)
        {
            Console.WriteLine($"Start downloading blob {blobName}");
            var response = await blobClient.DownloadAsync();
            Console.WriteLine($"Finish downloaded blob {blobName}");

            return response.Value.Content;
        }
        else
        {
            Console.WriteLine($"Blob {blobName} does not exist in container {containerName}.");
            return null;
        }
        }

        private async Task<string> GetAccessTokenAsync()
        {
            var clientId = "";
            var clientSecret = "";
            var tenantId = "";

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var tokenRequestContext = new TokenRequestContext(new string[] { "https://graph.microsoft.com/.default" });

            var accessTokenResult = await clientSecretCredential.GetTokenAsync(tokenRequestContext);

            return accessTokenResult.Token;
        }
    }
}
Azure Storage Accounts
Azure Storage Accounts
Globally unique resources that provide access to data management services and serve as the parent namespace for the services.
3,217 questions
Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
2,918 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,792 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Sumarigo-MSFT 46,441 Reputation points Microsoft Employee
    2024-09-02T16:33:54.1366667+00:00

    @angeline mary marchella Welcome to Microsoft Q&A Forum, Thank you for posting your query here!

    Apologies for the delay response!

    The issue you are experiencing with the ExistsAsync() method always returning false could be caused by a few different factors. Here are a few things you can check:

    1. Check the container and blob names: Make sure that the container and blob names are spelled correctly and match the names in your Azure Blob Storage account. It's possible that there is a typo or a naming mismatch that is causing the ExistsAsync() method to fail.
    2. Check the connection string: Make sure that the connection string you are using to create the BlobServiceClient object is correct and includes the correct account name and account key. You can verify this by checking the connection string in the Azure portal or by using the Azure Storage Explorer tool.
    3. Check the permissions: Make sure that the account key you are using to authenticate with Azure Blob Storage has the necessary permissions to read the container and blob. You can check this by verifying the access policies in the Azure portal or by using the Azure Storage Explorer tool.
    4. Check the blob tier: Make sure that the blob you are trying to access is not in the Archive tier. Blobs in the Archive tier are not immediately accessible and must be rehydrated before they can be read. You can check the blob tier in the Azure portal or by using the Azure Storage Explorer tool.

    BlobBaseClient.ExistsAsync(CancellationToken) Method

    BlobClient.Exists() throws exception when blob is missing

    var blobServiceClient = new BlobServiceClient(connectionString);
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    var blobClient = containerClient.GetBlobClient(blobName);
    
    var isExist = await blobClient.ExistsAsync();
    if (isExist)
    {
        Console.WriteLine("Blob exists.");
    }
    else
    {
        Console.WriteLine("Blob does not exist.");
    }
    

    If none of these solutions work, you can try using the DownloadAsync() method to download the blob directly instead of checking if it exists first. If the blob does not exist, the DownloadAsync() method will throw a RequestFailedException with a status code of 404 (Not Found).

    Please let us know if you have any further queries. I’m happy to assist you further.    


    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.

    0 comments No comments

  2. Nate Wetzel 0 Reputation points
    2024-10-30T20:02:33.32+00:00

    I think your issue is that you blob name starts with a forward slash: "/". Azure interprets this as a "no name" folder, which seems to be ignored by recent .Net versions.

    I have files with a forwards slash to start the blob name, and my application written in .Net 4.7 can get the blobs using BlockBlobClient. I can see the blob using Azure Storage Explorer, however the Azure portal shows no known blob with this name. I also have a .Net 8 application that the BlockBlobClient.Exists() also returns false.

    The Blob exists.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.