So far, we have seen creating containers and uploading blobs directly to the containers. You can read previous parts of this "Understanding Blob Storage" here:
Containers are basically like root folders on file systems and all the blobs that go into the container go to that root folder. To enable hierarchy for the subfolder you should use a prefix on the blob that you upload into the container.
Step 1
First, we will see how to do the same via the portal. While uploading a blob, in the advanced option you can see a provision to specify a specific folder to upload and it will create a new one if one we specified doesn’t exist.
Step 2
Browse for a file and click on upload and you can see a new folder has been created in our container and the new file added inside the container.
Step 3
Now we can create another subfolder in the container using our application. For that copy the following code to your Main method. In this code, we are going to copy a blob in the container to a subfolder. In the reference code to which the file has to be copied, we are prefixing the name of the subfolder to the filename.
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnection"));
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- CloudBlobContainer container = blobClient.GetContainerReference("images");
- container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
- CloudBlockBlob blockBlob = container.GetBlockBlobReference("img5.jpeg");
- CloudBlockBlob blockBlobCopy = container.GetBlockBlobReference("Sub Folder 2/img5.jpeg");
- var cb = new AsyncCallback(x => Console.WriteLine("blob copy completed"));
- blockBlobCopy.BeginStartCopy(blockBlob.Uri, cb, null);
- Console.ReadKey();
Step 4
Run the application and we can see the new folder has been created with the file copied inside
If you check the URL of the new file it will be also following the same path format, with the container name followed by the folder name followed by the actual file name.