c# - 我应该使用 BlobContainerClient 还是 BlobClient 还是两者都使用?

标签 c# azure

我对 C# azure sdk 感到困惑。

我想要实现的目标。

将文件从我的计算机上传到 azure 中的文件夹。

例如

本地

MyFiles 
   -- Folder1
     -- file.txt
     -- img.jpg
   -- Folder2
      -- file2.json
      -- test.png

Azure 结果

Container
     MyFiles 
           -- Folder1
             -- file.txt
             -- img.jpg
           -- Folder2
              -- file2.json
              -- test.png

所以我想在我的容器中使用 azure 相同的文件结构。

我是如何做的

var sasCred = new AzureSasCrdentials("sasurl");
var container = new BlobContainerClient(new Uri("containerUrl"), sasCred);

var allFiles = Directory.GetFiles("MyFilesFolderPath", "*", SearchOption.AllDirectories);

foreach(var file in files)
{
   var cloudFilePath = file.Replace("MyFilesFolderPath", string.Empty);
   var fullPath= $"MyFiles{cloudFilePath};

  using(var s = new MemoryStream(File.ReadAllBytes(file))
  {
     await container.UploadBlobAsync(fullPath,stream); 
  }
}

这似乎做了我需要它做的事情,尽管我注意到文件类型类似于“文件八位字节流”,而不是 .json/.png/txt 或任何它应该是的。

当我搜索时,它谈到使用 BlobCLient 来设置文件类型,但现在我确定是否应该使用 BlobContainerClient。

最佳答案

在这种情况下,您需要同时使用 BlobContainerClientBlobClient。执行此操作的方法是,使用 BlobContainerClient 和 blob 名称创建一个 BlobClient 实例(特别是 BlockBlobClient),并使用 UploadAsync方法在那里。

您的代码(未经测试)将类似于:

var sasCred = new AzureSasCrdentials("sasurl");
var container = new BlobContainerClient(new Uri("containerUrl"), sasCred);

var allFiles = Directory.GetFiles("MyFilesFolderPath", "*", SearchOption.AllDirectories);

foreach(var file in files)
{
   var cloudFilePath = file.Replace("MyFilesFolderPath", string.Empty);
   var fullPath= $"MyFiles{cloudFilePath};

  using (var s = new MemoryStream(File.ReadAllBytes(file))
  {
      var blockBlob = container.GetBlockBlobClient(fullPath);//Get BlockBlobClient instance
      var blobContentType = GetContentTypeFromFileSomehow(file);//Write a helper method to get the content type
      var headers = new BlobHttpHeaders() { ContentType = blobContentType};//Set content type header for blob.
      var blobUploadOptions = new BlobUploadOptions() { HttpHeaders = headers};
      await blockBlob.UploadAsync(s, blobUploadOptions);//Upload blob 
  }
}

关于c# - 我应该使用 BlobContainerClient 还是 BlobClient 还是两者都使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74894414/

相关文章:

c# - 在反射中循环遍历模型属性,然后使用 Html 帮助程序进行显示。如何取回具体属性(property)?

c# - 以其语言获取文化显示名称

azure - 创建 SSL 证书时出现意外错误 : certificate and private key does not have a matching public key: tls: private key does not match public key

azure - 以特定方式自定义 Azure 搜索评分

azure - 如何在AKS集群中创建Windows节点池?

c# - 查找字符串中空行的索引

c# - ASP.NET Core 移动后端 API [错误] : This appname. 找不到 azurewebsites.net 页面

c# - Web Api路由问题

azure - 如何从 RoleEntryPoint.OnStart() 获取 WebRole 站点根路径?

Azure DevOps 管道 - 输出文件的自定义名称