Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 770
sirdank Avatar asked Oct 01 '18 14:10

sirdank


2 Answers

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...");
   }
}
like image 178
Ivan Yang Avatar answered Sep 22 '22 12:09

Ivan Yang


Following the advice of Ivan Yang, I adapted my code using Azure.Storage.Files.Shares (Version=12.2.3.0).

Here's my contribution:

readonly string storageConnectionString = "yourConnectionString";
readonly string shareName = "yourShareName";

public string StoreFile(string dirName,string fileName, Stream fileContent)
{
    // Get a reference to a share and then create it
    ShareClient share = new ShareClient(storageConnectionString, shareName);
    share.CreateIfNotExists();

    // Get a reference to a directory and create it
    string[] arrayPath = dirName.Split('/');
    string buildPath = string.Empty;
    var tempoShare = share;
    ShareDirectoryClient directory = null; // share.GetDirectoryClient(dirName);
    // Here's goes the nested directories builder
    for (int i=0; i < arrayPath.Length; i++)
    {
        buildPath += arrayPath[i];
        directory = share.GetDirectoryClient(buildPath);
        directory.CreateIfNotExists();
        buildPath += '/';
    }
     // Get a reference to a file and upload it
    ShareFileClient file = directory.GetFileClient(fileName);
    using (Stream stream = fileContent)
    {
        file.Create(stream.Length);
        file.UploadRange(new HttpRange(0, stream.Length), stream);
    }
    return directory.Path;
}
like image 27
Hagen Avatar answered Sep 20 '22 12:09

Hagen