Skip to main content

Notifications

Finance | Project Operations, Human Resources, ...
Suggested answer

How to check folder is present in Azure blob container

(1) ShareShare
ReportReport
Posted on by 161
Hi Team,
 
Inside the azure blob container name i am having multiple folders, like below.
 
ContinerName/Folder1/Folder2
 
In case of any folder is missing i would like to show some error message.
 
In above if Folder2 is missing show error like folder is not present.
 
Below is the code which i am using.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;


 public void checkFolderName(str _filePath)
 {
     CloudBlobContainer blobcontainer;
     CloudBlobClient    blobClient;
      
     
     var credential     = new StorageCredentials("StorageAccountName", "StorageAccessKey");
     var storageAccount = new CloudStorageAccount(credential, true);
     blobClient         = storageAccount.CreateCloudBlobClient();
     blobcontainer      = blobClient.GetContainerReference(_filePath);
  }
 
Please let me know how to achieve this.
  • Martin Dráb Profile Picture
    Martin Dráb 230,370 Most Valuable Professional on at
    How to check folder is present in Azure blob container
    CU21091228-0, you're indeed calling GetBlobs incorrectly. Your code assumes that the method has a single string parameter, but that's not true. Look at the documentation of GetBlobs() method to see how it's defined. Also, Jones has given you an example in the meantime.
  • How to check folder is present in Azure blob container
    I have written an annotated example job as a learning opportunity for you.
     
    You will be able to adapt this to your method, and rewrite it so it matches your coding style, I have a really odd one if I'm not caffeinated properly...
     
    Do let me know if you have any questions
     
     
    //Example for https://community.dynamics.com/forums/thread/details/?threadid=3901f86c-6485-ef11-ac21-6045bda935ce
    
    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    
    internal final class CheckDirectory
    {
        //This example uses Azure.Storage.Blobs, as Microsoft.WindowsAzure.Storage will be deprecated in the near future
        //You can find the documentation here: https://www.nuget.org/packages/Azure.Storage.blobs/
        //Samples here: https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/storage/Azure.Storage.Blobs/samples
        //NOTICE: I am using a connection string in this example, please adapt it to how you plan to authenticate
        public static void Main(Args _args)
        {
            //Connection string
            str connectionString    = "https://*connectionString*";
    
            //Blob prefix (As in your question, folder)
            str prefix              = "foo/bar/bas";
    
            //Initializes a new blob container client: https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.blobcontainerclient?view=azure-dotnet
            //Due to X++ limitations, .Net method parameters cannot be defaulted
            if (new BlobContainerClient(new System.Uri(connectionString))
                //Lists blobs in directory
                .GetBlobs(             
                    //Blob traits: https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.models.blobtraits?view=azure-dotnet
                    BlobTraits::None,
                    //Blob states: https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.models.blobstates?view=azure-dotnet
                    BlobStates::None,
                    //Blob prefix
                    prefix,
                    //Cancelation token (Note: Not used)
                    //https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=net-8.0
                    new System.Threading.CancellationToken(false))
                //Gets enumerator
                .GetEnumerator()
                //Iterate enumerator. Will return false at end of enumerator: https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenext?view=net-8.0
                .MoveNext())
            {
                info("Directory found!");
            }
        }
    }
  • CU21091228-0 Profile Picture
    CU21091228-0 161 on at
    How to check folder is present in Azure blob container
    I have added below code.
    Using Azure.Storage.Blobs;
    
    public void checkFolderName(str _filePath, str _containerName)
    {
       BlobContainerClient blobContainerClient;
    
       //
       blobContainerClient.GetBlobs(_filePath);
    }
    Below error i am getting.
  • Martin Dráb Profile Picture
    Martin Dráb 230,370 Most Valuable Professional on at
    How to check folder is present in Azure blob container
    I think I see your problem. Your code (the call of ListBlobs()) assumes that you're using Microsoft.Azure.Storage.Blob.CloudBlobDirectory, but you aren't. You're using CloudBlobDirectory from Microsoft.WindowsAzure.Storage.Blob namespace.

    Note that the latest library for this purpose is Azure.Storage.Blobs. I think that the solution there is using BlobContainerClient.GetBlobs() with the folder path in the prefix parameter.
  • Martin Dráb Profile Picture
    Martin Dráb 230,370 Most Valuable Professional on at
    How to check folder is present in Azure blob container
    I'm sorry, but "Ax is not supporting blobs.count()" is not a good description of a problem. Please tell us what happened. For example, did you get a compilation error a runtime exception? What did the error message said?
  • CU21091228-0 Profile Picture
    CU21091228-0 161 on at
    How to check folder is present in Azure blob container
    In Azure blob container having multiple folders, i would like to check those folder is present or not, if not present throw a error.
    Below us my AX code.
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Blob;
    using Microsoft.WindowsAzure.Storage.File;
    
    
     public void checkFolderName(str _filePath, str _containerName)
     {
         CloudBlobContainer blobcontainer;
         CloudBlobClient    blobClient;
          
         
         var credential     = new StorageCredentials("StorageAccountName", "StorageAccessKey");
         var storageAccount = new CloudStorageAccount(credential, true);
         blobClient         = storageAccount.CreateCloudBlobClient();
         blobcontainer      = blobClient.GetContainerReference(_containerName);
         CloudBlobDirectory cloudBlobDirectory = blobContainer.GetBlobDirectoryReference(_filePath);
      }
     
    I try below code, Ax is not supporting blobs.count()
    var blobs = CloudBlobDirectory.ListBlobs(false, 0, null, null);
    boolean directoryExists = blobs.Count() > 0;
  • Martin Dráb Profile Picture
    Martin Dráb 230,370 Most Valuable Professional on at
    How to check folder is present in Azure blob container
    Split it to two calls. For example:
    var blobs = CloudBlobDirectory.ListBlobs();
    boolean directoryExists = blobs.Count() > 0;
    It'll likely fix your problem. If not, please describe the problem to us.
  • CU21091228-0 Profile Picture
    CU21091228-0 161 on at
    How to check folder is present in Azure blob container
    I try like below.
     
    boolean directoryExists = CloudBlobDirectory.ListBlobs().Count() > 0
    But Ax is not support .Count() after ListBlobs().
     
     
     
     
  • Suggested answer
    Martin Dráb Profile Picture
    Martin Dráb 230,370 Most Valuable Professional on at
    How to check folder is present in Azure blob container
     
    In blob storage, directories don't exist as an item by themselves. What you can have is a blob that has a name that can be interpreted as being in a directory. If you look at the underlying REST API you'll see that that there's nothing in there about directories. What the storage client library is doing for you is searching for blobs that start with the directory name then the delimiter e.g. "DirectoryA/DirectoryB/FileName.txt". What this means is that for a directory to exist it must contain a blob. To check if the directory exists you can try either:
     
    var blobDirectory = client.GetBlobDirectoryReference("Path_to_dir");
    bool directoryExists = blobDirectory.ListBlobs().Count() > 0
     
    or
     
    bool directoryExists = client.ListBlobsWithPrefix("DirectoryA/DirectoryB/").Count();
  • CU21091228-0 Profile Picture
    CU21091228-0 161 on at
    How to check folder is present in Azure blob container
    Below code i am using.
    CloudBlobDirectory cloudBlobDirectory = blobContainer.GetBlobDirectoryReference('Folder1/Folder2');
    
    if (!cloudBlobDirectory)
    {
       throw error ("Folder name not found");
    }
    In case folder path is not present i am not getting any error, please let me know where i am wrong.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

News and Announcements

Announcing Category Subscriptions!

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Verified Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,359 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,370 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans