I am trying to upload a file to my Azure File Storage account.
This is my code:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myConnString");
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("myFileStorage");
if (await share.ExistsAsync())
{
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("/folder1/folder2/");
CloudFile file = sampleDir.GetFileReference("fileName.jpg");
using Stream fileStream = new MemoryStream(data);
await file.UploadFromStreamAsync(fileStream);
}
I am getting this error:
The specified parent path does not exist.
After this line:
CloudFile file = sampleDir.GetFileReference("fileName");
the file
has this uri:
https://myFileStorage.file.core.windows.net/myFileStorage/folder1/folder2/fileName.jpg
i.e. as expected.
Currently my file storage is empty, there are no files/folders. How do I create my custom folders if they do not already exist?
If you're using WindowsAzure.Storage, version 9.3.3 and create only one directory(no sub-directories), you can directly use CreateIfNotExistsAsync()
method to create a directory.
But here is one thing you should remember, for file share, the SDK does not support create a directory which contains subdirectories, like "folder1/folder2" in your case. The solution for that is create these directories one by one.
Here is the sample code for your case, create a directory with sub-directories:
static async void UploadFiles()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection_string");
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("file_share");
if (await share.ExistsAsync())
{
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
//define your directories like below:
var myfolder = "folder1/folder2";
var delimiter = new char[] { '/' };
var nestedFolderArray = myfolder.Split(delimiter);
for (var i = 0; i < nestedFolderArray.Length; i++)
{
rootDir = rootDir.GetDirectoryReference(nestedFolderArray[i]);
await rootDir.CreateIfNotExistsAsync();
Console.WriteLine(rootDir.Name + " created...");
}
CloudFile file = rootDir.GetFileReference("fileName.jpg");
byte[] data = File.ReadAllBytes(@"file_local_path");
Stream fileStream = new MemoryStream(data);
await file.UploadFromStreamAsync(fileStream);
}
}
The test result=> directories are created and file uploaded into azure: