You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#无法在指定Blob存储路径下上传文件求助

问题原因

Azure Blob存储中,a/b这类带斜杠的是虚拟目录,并非容器名称。你错误地把虚拟路径当成容器名传入CreateBlobContainer,导致系统创建了一个名为a/b的新容器,上传的文件自然直接存在这个容器里,而非你期望的根容器下的a/b虚拟路径中。

修复方案
  • 修正容器名称:容器名不能包含斜杠,填写你实际要使用的根容器名称(比如mycontainer,需替换为你的真实容器名)。
  • 指定Blob完整虚拟路径:上传时把虚拟目录路径和文件名拼接,作为Blob的名称传入UploadBlob方法。
  • 避免重复创建容器:如果容器已存在,改用CreateIfNotExists方法,防止触发报错。
修正后的代码
static string connectionString = "myconnection string";
// 替换为你的根容器名称,不能带斜杠
static string containerName = "mycontainer";
static void Main(string[] args)
{
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    // 使用CreateIfNotExists避免容器已存在时报错
    BlobContainerClient containerClient = blobServiceClient.CreateBlobContainerIfNotExists(containerName);

    var files = Directory.GetFiles(@"C:/root");
    foreach (var file in files)
    {
        string fileName = Path.GetFileName(file);
        // 拼接虚拟目录和文件名,作为Blob的完整路径
        string blobPath = $"a/b/{fileName}";
        using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(file)))
        {
            containerClient.UploadBlob(blobPath, stream);
        }
        Console.WriteLine($"{file} 已上传至 {blobPath}");
    }
    Console.Read();
}
额外说明
  • 虚拟目录不需要提前创建,上传Blob时如果路径不存在,Azure会自动生成对应的虚拟目录结构。
  • 如果需要对虚拟目录进行管理,可以通过Blob名称的前缀来筛选操作。

内容的提问来源于stack exchange,提问作者penchalaiah narakatla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:49:11