Este tópico descreve como excluir um único objeto ou vários objetos simultaneamente.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).
Para excluir um objeto, você precisa da permissão
oss:DeleteObject. Para mais informações, consulte Conceder uma política personalizada.
Excluir um único objeto
O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado examplebucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Delete the object.
client.DeleteObject(bucketName, objectName);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete object failed. {0}", ex.Message);
}
Excluir vários objetos
Você pode excluir até 1.000 objetos por vez.
O resultado pode ser retornado nos dois modos a seguir. Selecione o modo de retorno conforme sua necessidade.
verbose: Se quietMode não for especificado ou estiver definido como false, o sistema retorna uma lista de todos os objetos excluídos. Este é o modo de retorno padrão.
quiet: Se quietMode estiver definido como true, o sistema não retorna nenhum corpo de mensagem.
O código a seguir mostra como excluir vários objetos específicos de um bucket chamado examplebucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Specify the paths of multiple objects that you want to delete. Do not include the bucket name in the full paths.
var keys = new List<string>();
keys.Add("exampleobject.txt");
keys.Add("testdir/sampleobject.txt");
// Leave quietMode empty or set quietMode to false to return the list of deleted objects.
var quietMode = false;
var request = new DeleteObjectsRequest(bucketName, keys, quietMode);
// Delete multiple objects.
var result = client.DeleteObjects(request);
if ((!quietMode) && (result.Keys != null))
{
foreach (var obj in result.Keys)
{
Console.WriteLine("Delete successfully : {0} ", obj.Key);
}
}
Console.WriteLine("Delete objects succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete objects failed. {0}", ex.Message);
}
Referências
-
Excluir um único objeto
Para obter mais informações sobre a operação de API usada para excluir um único objeto, consulte DeleteObject.
-
Excluir vários objetos
Para obter o código de exemplo completo usado para excluir vários objetos, visite o GitHub.
Para obter mais informações sobre a operação de API usada para excluir vários objetos, consulte DeleteMultipleObjects.