Search code examples
asp.netazureazure-storage-files

Azure file storage - Upload file in nested directories


I want to upload files but in a nested folder environment. I have no problem to create a directory and upload a file but when using nested directories I got a storage exception when trying to create folders. Here is a code example.

   CloudFileDirectory rootDirectory = FileShare.GetRootDirectoryReference();
   if (rootDirectory.Exists())
   {
       cloudFileDirectory = rootDirectory.GetDirectoryReference("Folder/SubFolder"); 

        cloudFileDirectory.CreateIfNotExists(); //Exception occur

        var file = cloudFileDirectory.GetFileReference("File.txt");
   }

Do I have to create a method that create directory for directory or is there a more simple solution?


Solution

  • Do I have to create a method that create directory for directory or is there a more simple solution?

    Yes, you would need to do that. You can't specify a folder structure and have SDK take care of it for you. Please take a look at sample code below for one approach.

        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();
            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...");
            }
        }