当没有子目录时,我可以从 Azure 文件共享下载所有文件,但只要子目录位于目录内,代码就会崩溃并出现错误:
Azure.RequestFailedException: 'The specified resource does not exist.
RequestId:0ccda3e3-d01a-00ae-42a5-21fad0000000
Time:2024-10-18T21:31:20.6046993Z
Status: 404 (The specified resource does not exist.)
ErrorCode: ResourceNotFound
代码:(我尝试做的是使用 item.IsDirectory 但这不会跳过目录)
public void DownloadALlFiles()
{
// Get a connection string to our Azure Storage account.
string connectionString = "connectionstring";
// Get a reference to a share named "sample-share"
ShareClient share = new ShareClient(connectionString, "clientshare");
// Get a reference to a directory named "sample-dir"
ShareDirectoryClient dir = share.GetDirectoryClient("directory/");
foreach (ShareFileItem item in dir.GetFilesAndDirectories())
{
Console.WriteLine(item.Name);
// Get a reference to a file named "sample-file" in directory "sample-dir"
ShareFileClient file = dir.GetFileClient(item.Name);
// Download the file
ShareFileDownloadInfo download = file.Download();
using (FileStream stream = File.Open("localpath"+ item.Name, FileMode.CreateNew))
{
download.Content.CopyTo(stream);
stream.FlushAsync();
stream.Close();
}
// await file.DeleteAsync();
}
//Console.ReadLine();
}
让我详细说明一下,所以我只想下载文件而忽略子目录。当不存在子目录时,代码会很好地下载所有文件。但是,只要存在子目录,它就会崩溃并显示上面的错误。我消除了访问问题以及其他可能常见的问题。
我尝试使用以下代码来跳过目录,但这也跳过了文件。
if (item.IsDirectory)
{
}
我很确定使用 item.IsDirectory 是一个解决方案,但我不知道如何有效地集成它。
您的问题只是创建一个方法的问题,然后可以递归调用该方法以处理子目录,例如:
public void DownloadFiles(ShareDirectoryClient dir)
{
foreach (ShareFileItem it in dir.GetFilesAndDirectories())
{
if (it.IsDirectory)
{
ShareDirectoryClient subDir = dir.GetSubdirectoryClient(item.Name);
string subPath = Path.Combine("localpath", item.Name);
Directory.CreateDirectory(subPath);
DownloadAllFiles(subDIr, subPath);
}
else
{
// Your normal file download code
}
}
}
这个想法是以一种您可以从方法本身内部调用它的方式创建方法,以便正确处理子目录。
希望这有帮助。