c# - 如何在blob存储中上传具有原始文件夹结构的文件?

标签 c# .net azure azure-blob-storage

下面的代码会将文件上传到 Blob 存储

// intialize BobClient 
            Azure.Storage.Blobs.BlobClient blobClient = new Azure.Storage.Blobs.BlobClient(
                connectionString: connectionString, 
                blobContainerName: "mycrmfilescontainer", 
                blobName: "sampleBlobFileTest");
             
            // upload the file
            blobClient.Upload(filePath);

但是如何上传所有文件并维护其文件夹结构呢?

我有 site 文件夹,其中包含所有 html 文件 + 图像 + css 文件夹以及网站的相关文件。

我想将完整的 site 文件夹上传到 blob 存储上,请建议方法。

最佳答案

请看下面的代码:

using System.Threading.Tasks;
using System.IO;
using Azure.Storage.Blobs.Specialized;

namespace SO71558769
{
    class Program
    {

        private const string connectionString = "connection-string";
        
        private const string containerName = "container-name";

        private const string directoryPath = "C:\temp\site\";
        
        static async Task Main(string[] args)
        {
            var files = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
            for (var i=0; i<files.Length; i++)
            {
                var file = files[i];
                var blobName = file.Replace(directoryPath, "").Replace("\\", "/");
                BlockBlobClient blobClient = new BlockBlobClient(connectionString, containerName, blobName);
                using (var fs = File.Open(file, FileMode.Open))
                {
                    await blobClient.UploadAsync(fs);
                }
            }
        }
    }
}

本质上,这个想法是获取文件夹中所有文件的列表,然后循环该集合并上传每个文件。

要获取 blob 名称,您只需在文件名中找到目录路径并将其替换为空字符串即可获取 blob 名称(例如,如果完整文件路径为 C:\temp\site\html\index.html,那么 blob 名称将为 `html\index.html)。

如果您使用的是 Windows,那么您还需要将 \ 分隔符替换为 / 分隔符,以便获得最终的 blob 名称 html/index .html.

关于c# - 如何在blob存储中上传具有原始文件夹结构的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71558769/

相关文章:

.net - 为什么 Azure 服务总线不受防火墙和代理的影响?

azure - 如何将云上托管的 MySQL 数据库连接到 Azure 数据工厂?

azure - 如何以编程方式设置 Azure 计算服务的实例计数

c# - 如何将 3x2 矩阵转换为 4x4 矩阵?

c# - 在 LINQPad 中将 SQL 查询结果转换为 C# 字典

c# - 如何处理窗体的 KeyPress 事件?

.NET View 状态解码器

具有简单数据库的 C# 应用程序?

c# - 日期转换问题

c# - 编译时禁用 Dll 文化文件夹