使用 .NET 删除和还原 Blob 容器
本文介绍了如何使用适用于 .NET 的 Azure 存储客户端库删除容器。 如果已启用容器软删除,则可以还原已删除的容器。
先决条件
- 本文假设已经设置了项目来使用适用于 .NET 的 Azure Blob 存储客户端库。 要了解有关设置项目的信息,包括包安装、添加
using
指令和创建授权客户端对象,请参阅开始使用 Azure Blob 存储和 .NET。 - 授权机制必须具有删除 blob 容器或还原软删除容器的权限。 若要了解详细信息,请参阅以下 REST API 操作的授权指南:
删除容器
若要在 .NET 中删除容器,请使用以下方法之一:
如果该容器不存在,Delete 和 DeleteAsync 方法将引发异常 。
DeleteIfExists 和 DeleteIfExistsAsync 方法返回一个指示是否已删除容器的布尔值。 如果指定的容器不存在,则这些方法将返回 False,指示未删除该容器。
删除容器后,至少在 30 秒内无法使用相同的名称创建容器。 尝试使用相同的名称创建容器将会失败,并出现 HTTP 错误代码 409(冲突)。 针对容器或其包含的 Blob 执行任何其他操作将会失败,并出现 HTTP 错误代码 404(未找到)。
以下示例删除指定的容器,并在该容器不存在时处理异常:
//-------------------------------------------------
// Delete a container
//-------------------------------------------------
private static async Task DeleteSampleContainerAsync(BlobServiceClient blobServiceClient, string containerName)
{
BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName);
try
{
// Delete the specified container and handle the exception.
await container.DeleteAsync();
}
catch (RequestFailedException e)
{
Console.WriteLine("HTTP error code {0}: {1}",
e.Status, e.ErrorCode);
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
以下示例演示如何删除以指定的前缀开头的所有容器。
//-------------------------------------------------
// Delete all containers with the specified prefix
//-------------------------------------------------
private static async Task DeleteContainersWithPrefixAsync(BlobServiceClient blobServiceClient, string prefix)
{
Console.WriteLine("Delete all containers beginning with the specified prefix");
try
{
foreach (BlobContainerItem container in blobServiceClient.GetBlobContainers())
{
if (container.Name.StartsWith(prefix))
{
Console.WriteLine("\tContainer:" + container.Name);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(container.Name);
await containerClient.DeleteAsync();
}
}
Console.WriteLine();
}
catch (RequestFailedException e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
还原软删除的容器
为存储帐户启用容器软删除后,容器及其内容被删除后可以在指定的保持期内恢复。 可以通过调用 BlobServiceClient 类的以下方法之一来还原被软删除的容器。
下面的示例查找已删除的容器,获取该已删除容器的版本 ID,然后将该 ID 传递到 UndeleteBlobContainerAsync 方法以还原该容器。
public static async Task RestoreContainer(BlobServiceClient client, string containerName)
{
await foreach (BlobContainerItem item in client.GetBlobContainersAsync
(BlobContainerTraits.None, BlobContainerStates.Deleted))
{
if (item.Name == containerName && (item.IsDeleted == true))
{
try
{
await client.UndeleteBlobContainerAsync(containerName, item.VersionId);
}
catch (RequestFailedException e)
{
Console.WriteLine("HTTP error code {0}: {1}",
e.Status, e.ErrorCode);
Console.WriteLine(e.Message);
}
}
}
}
资源
若要详细了解如何使用适用于 .NET 的 Azure Blob 存储客户端库来删除容器,请参阅以下资源。
REST API 操作
Azure SDK for .NET 包含基于 Azure REST API 而生成的库,允许你通过熟悉的 .NET 范例与 REST API 操作进行交互。 用于删除或还原容器的客户端库方法使用以下 REST API 操作: