Azure文件存储:创建嵌套目录

时间:2018-10-01 14:30:10

标签: c# azure-files

我的代码如下

CloudFileClient client = ...;

client.GetShareReference("fileStorageShare")
    .GetRootDirectoryReference()
    .GetDirectoryReference("one/two/three")
    .Create();

如果目录一或两个不存在,则会发生此错误。有没有办法通过一次调用创建这些嵌套目录?

2 个答案:

答案 0 :(得分:3)

这是不可能的。 SDK不支持这种方式,您应该一个一个地创建它们。

问题已提交here

如果要一个一个地创建它们,可以使用以下示例代码:

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();

   //Specify the nested folder
   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...");
   }
}

答案 1 :(得分:0)

按照Ivan Yang的建议,我使用Azure.Storage.Files.Shares(版本= 12.2.3.0)修改了我的代码。

这是我的贡献:

readonly string storageConnectionString = "yourConnectionString";
readonly string shareName = "yourShareName";

public string StoreFile(string dirName,string fileName, Stream fileContent)
{
    // Get a reference to a share and then create it
    ShareClient share = new ShareClient(storageConnectionString, shareName);
    share.CreateIfNotExists();

    // Get a reference to a directory and create it
    string[] arrayPath = dirName.Split('/');
    string buildPath = string.Empty;
    var tempoShare = share;
    ShareDirectoryClient directory = null; // share.GetDirectoryClient(dirName);
    // Here's goes the nested directories builder
    for (int i=0; i < arrayPath.Length; i++)
    {
        buildPath += arrayPath[i];
        directory = share.GetDirectoryClient(buildPath);
        directory.CreateIfNotExists();
        buildPath += '/';
    }
     // Get a reference to a file and upload it
    ShareFileClient file = directory.GetFileClient(fileName);
    using (Stream stream = fileContent)
    {
        file.Create(stream.Length);
        file.UploadRange(new HttpRange(0, stream.Length), stream);
    }
    return directory.Path;
}