接受的答案现在似乎已经过时了。以下代码段使用最新的 sdk。为了获得更好的性能它被实现为 for 循环而不是递归算法。它会发现位于 的所有文件和文件夹directoryPath
。发现文件后,您可以将其删除。
var rootDirectory = directoryPath != null
? shareClient.GetDirectoryClient(directoryPath)
: shareClient.GetRootDirectoryClient();
var remaining = new Queue<ShareDirectoryClient>();
remaining.Enqueue(rootDirectory);
while (remaining.Count > 0)
{
var shareDirectoryClient = remaining.Dequeue();
await foreach (var item in shareDirectoryClient.GetFilesAndDirectoriesAsync())
{
if (!item.IsDirectory)
{
var shareFileClient = shareDirectoryClient.GetFileClient(item.Name);
files.Add(shareFileClient);
// do what you want
await shareFile.DeleteAsync();
}
if (item.IsDirectory)
{
remaining.Enqueue(shareDirectoryClient.GetSubdirectoryClient(item.Name));
// do what you want
await shareFile.DeleteAsync();
}
}
}
在上面的代码中,directory
可能是null
要删除的目录或路径。
要初始化客户端,可以使用以下方法:
AccountSasBuilder sas = new AccountSasBuilder
{
Services = AccountSasServices.Files,
ResourceTypes = AccountSasResourceTypes.All,
ExpiresOn = DateTimeOffset.UtcNow.AddMonths(1)
};
sas.SetPermissions(AccountSasPermissions.List | AccountSasPermissions.Read | AccountSasPermissions.Delete);
var credential = new StorageSharedKeyCredential(AccountName, AccountKey);
var sasUri = new UriBuilder(AccountUri);
sasUri.Query = sas.ToSasQueryParameters(credential).ToString();
var shareServiceClient = new ShareServiceClient(sasUri.Uri);
var shareClient = shareServiceClient.GetShareClient(FileShareName);