Henke Henke - 9 days ago 9
ASP.NET (C#) Question

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?

Answer

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