.NET环境下统计Azure Blob Storage指定文件夹内文件总数问题
ASP.NET 统计 Azure Blob Storage 指定路径文件数量问题
需求背景
在ASP.NET项目开发中,需要统计Azure Blob Storage指定文件夹下的总文件数量,目标文件夹路径为container_one/year/month/day/hour。
初始实现与报错
测试代码
string path = "container_one/year/month/day/hour"; int totalItems = 0; BlobContainerClient blobFolder = new BlobServiceClient(connectionString).GetBlobContainerClient(path); foreach(var blob in blobFolder){ totalItems++; } Console.WriteLine(totalItems);
异常信息
System.AggregateException: 'One or more errors occurred. (The requested URI does not represent any resource on the server.
已确认上述路径在服务器上真实存在。
问题定位与修复
错误原因
代码未等待blobFolder资源完成加载,在实例化BlobServiceClient并获取容器客户端的逻辑中缺少await关键字,导致资源未初始化完成就执行后续遍历操作,触发资源不存在报错。
修复后代码
string path = "container_one/year/month/day/hour"; int totalItems = 0; BlobContainerClient blobFolder = await new BlobServiceClient(connectionString).GetBlobContainerClient(path); foreach(var blob in blobFolder){ totalItems++; } Console.WriteLine(totalItems);
内容的提问来源于stack exchange,提问作者schweppes0x
相关产品推荐
相关产品推荐

