Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir objetos (C# SDK V2)

Última atualização: Sep 25, 2026

Este tópico descreve como usar o OSS C# SDK para excluir um único objeto ou múltiplos objetos.

Precauções

  • O código de exemplo neste tópico usa a região China (Hangzhou) (cn-hangzhou) como referência e utiliza o endpoint público por padrão. Para acessar o OSS a partir de outro serviço da Alibaba Cloud na mesma região, use o endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte OSS regions and endpoints.

  • Os exemplos neste tópico demonstram como ler credenciais de acesso a partir de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.

  • Para excluir um objeto, você precisa ter a permissão oss:DeleteObject. Para mais informações, consulte Grant custom permissions to a RAM user.

Código de exemplo

Delete a single object

using OSS = AlibabaCloud.OSS.V2;  // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-hangzhou";  // Required. Set the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string;  // Optional. Specify the domain name used to access the OSS service. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name";  // Required. The name of the destination bucket.
var key = "your object name";  // Required. The name of the destination object.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;   
// If an endpoint is specified, it overwrites the default endpoint. 
if(endpoint != null) 
{
    cfg.Endpoint = endpoint;
} 

// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg); 

// Call the DeleteObjectAsync method to delete the destination object.
var result = await client.DeleteObjectAsync(new OSS.Models.DeleteObjectRequest()
{
    Bucket = bucket,
    Key = key,
});

// Print the result information.
Console.WriteLine("DeleteObject done");   // A message indicating that the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}");  // The HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}");  // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:");  // The response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));  // Traverse and print all response headers.

Delete multiple objects

using OSS = AlibabaCloud.OSS.V2;  // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-hangzhou";  // Required. Set the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string;  // Optional. Specify the domain name used to access the OSS service. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name";  // Required. The bucket name.
var keys = new List<String>  // Required. The destination objects to be deleted.
{
    "your object key1",
    "your object key2",
    "your object key3"
};

// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;   
// If an endpoint is specified, it overwrites the default endpoint. 
if(endpoint != null) 
{
    cfg.Endpoint = endpoint;
} 

// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg);

// Create a collection of objects to be deleted.
var objects = new List<OSS.Models.DeleteObject>();
// Traverse the list of object keys to be deleted (skip if keys is null).
foreach (var item in keys ?? [])
{
    objects.Add(new OSS.Models.DeleteObject()
    {
        Key = item,
    });
}

// Call the DeleteMultipleObjectsAsync method to execute a batch deletion request.
var result = await client.DeleteMultipleObjectsAsync(new OSS.Models.DeleteMultipleObjectsRequest()
{
    Bucket = bucket,
    Objects = objects
});

// Print the result information.
Console.WriteLine("DeleteMultipleObjects done");  // A message indicating that the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}");  // The HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}");  // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:");  // The response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));  // Traverse and print all response headers.
Console.WriteLine("Key to be deleted:");  
keys?.ToList().ForEach(x => Console.WriteLine(x));  // Print the list of deleted objects.

Referências

Para o código de exemplo completo, consulte delete_object.cs.