Eut*_*rpy 2 c# azure azure-storage azure-storage-files
我正在尝试将文件上传到我的 Azure 文件存储帐户。
这是我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
指定的父路径不存在。
在这一行之后:
CloudFile file = sampleDir.GetFileReference("fileName");
Run Code Online (Sandbox Code Playgroud)
在file有这个URI:
https://myFileStorage.file.core.windows.net/myFileStorage/folder1/folder2/fileName.jpg
Run Code Online (Sandbox Code Playgroud)
即正如预期的那样。
目前我的文件存储是空的,没有文件/文件夹。如果自定义文件夹尚不存在,如何创建它们?
如果您使用的是WindowsAzure.Storage 版本 9.3.3并且仅创建一个目录(没有子目录),则可以直接使用CreateIfNotExistsAsync()方法创建目录。
但是您应该记住一件事,对于文件共享,SDK 不支持创建包含子目录的目录,例如您的情况下的“folder1/folder2”。解决方案是一一创建这些目录。
这是您案例的示例代码,创建一个包含子目录的目录:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
测试结果=> 目录被创建并将文件上传到 azure:
| 归档时间: |
|
| 查看次数: |
754 次 |
| 最近记录: |