.NET Framework 4.8 C#下载Azure文件共享遇子目录崩溃问题
解决Azure文件共享下载时子目录导致的404错误
问题根源:你的代码会遍历目标目录下的所有资源(包括文件和子目录),但当你用dir.GetFileClient(item.Name)去获取子目录的引用,再调用Download()时,Azure会返回404——因为子目录不是文件资源。
正确的处理方式是遍历前先判断资源类型,跳过所有子目录,只处理文件,核心就是用item.IsDirectory做过滤。修正后的代码如下:
public void DownloadAllFiles() { // 替换为你的存储账户连接字符串 string connectionString = "connectionstring"; // 替换为你的文件共享名称 ShareClient share = new ShareClient(connectionString, "clientshare"); // 替换为目标目录路径(末尾斜杠可加可不加) ShareDirectoryClient dir = share.GetDirectoryClient("directory"); foreach (ShareFileItem item in dir.GetFilesAndDirectories()) { Console.WriteLine(item.Name); // 跳过子目录,仅处理文件 if (item.IsDirectory) { continue; } // 获取文件引用 ShareFileClient file = dir.GetFileClient(item.Name); // 下载文件 ShareFileDownloadInfo download = file.Download(); // 用Path.Combine避免路径拼接错误,替换为你的本地目标路径 string localFilePath = Path.Combine(@"localpath", item.Name); using (FileStream stream = File.Open(localFilePath, FileMode.CreateNew)) { download.Content.CopyTo(stream); stream.Flush(); } } }
额外注意点:
- 拼接本地路径时用
Path.Combine()替代直接字符串拼接,避免路径分隔符错误 - 原代码中
FlushAsync()未加await且方法为同步类型,改用同步Flush()更合理 - 确保
localpath是有效本地目录,且程序拥有写入权限
内容的提问来源于stack exchange,提问作者Preyasha Patel
相关产品推荐
相关产品推荐

