Intro

In the previous post I showed how to work with Azure File Service shares from code. In this post I am going how to work with Azure File Service directories.

Prerequisites

Refer to previous posts to get started with Azure File Service.

Code

Azure File Service supports files and folders, there is a special folder - root folder. To get a reference to the root folder run the following code:

 var share = fileClient.GetShareReference($"share1");
var root = share.GetRootDirectoryReference();

This folder always exists for any file share and you can't delete it. Consider the following example:

var root = share.GetRootDirectoryReference();
root.Delete();

This code throws exception:

The remote server returned an error: (405) Method Not Allowed.

Root folder has methods thay you can use to access ordinary files and folders. Take a look on the following code:

var share = fileClient.GetShareReference($"share2");
share.CreateIfNotExists();
var root = share.GetRootDirectoryReference();
var dir = root.GetDirectoryReference("dir");
dir.CreateIfNotExists();

This code creates a new directory called "dir" in the root directory. The following code creates 50 directories inside "dir":

for (var i = 0; i < 50; i++)
{
    var subDir = dir.GetDirectoryReference($"sub-dir-{i}");
    subDir.CreateIfNotExists();
}

To get list of directories use the following code:

var dirs = dir.ListFilesAndDirectories();
Console.WriteLine(dirs.Count());

You can delete all sub-directories in a similar way:

var subdirs = dir.ListFilesAndDirectories().Where(item => item is CloudFileDirectory).Cast<CloudFileDirectory>();
foreach (var cfd in subdirs)
{
    cfd.DeleteIfExists();
}

Summary

In this post I have showed how to work with Azure File Service directories and provided basic code samples. In the next post I will show how to work with files.


;