Search code examples
c#azureazure-files

Azure File Storage: Create nested directories


My code looks like this

CloudFileClient client = ...;

client.GetShareReference("fileStorageShare")
    .GetRootDirectoryReference()
    .GetDirectoryReference("one/two/three")
    .Create();

This errors if directories one or two don't exist. Is there a way to create these nested directories with a single call?


Solution

  • It is impossible. The SDK does not support it this way, you should create them one by one.

    A issue has already submitted here.

    If you wanna create them one by one, you can use the following sample code:

    static void NestedDirectoriesTest()
    {
       var cred = new StorageCredentials(accountName, accountKey);
       var account = new CloudStorageAccount(cred, true);
       var client = account.CreateCloudFileClient();
       var share = client.GetShareReference("temp2");
       share.CreateIfNotExists();
       var cloudFileDirectory = share.GetRootDirectoryReference();
    
       //Specify the nested folder
       var nestedFolderStructure = "Folder/SubFolder";
       var delimiter = new char[] { '/' }; 
       var nestedFolderArray = nestedFolderStructure.Split(delimiter);
       for (var i=0; i<nestedFolderArray.Length; i++)
       {
           cloudFileDirectory = cloudFileDirectory.GetDirectoryReference(nestedFolderArray[i]);
           cloudFileDirectory.CreateIfNotExists();
           Console.WriteLine(cloudFileDirectory.Name + " created...");
       }
    }