Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir objetos (OSS SDK for C# 1.0)

Última atualização: Jul 03, 2026

Este tópico descreve como excluir um único objeto, vários objetos e objetos cujos nomes contêm um prefixo especificado de um bucket com versionamento.

Observações

  • Este tópico utiliza 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 a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).

  • A exclusão de um objeto requer a permissão oss:DeleteObject. Para obter mais informações, consulte Conceder uma política personalizada.

Comportamento de exclusão em buckets com versionamento

Ao excluir um objeto de um bucket com versionamento, decida se deseja especificar um ID de versão.

  • Excluir um objeto sem especificar um ID de versão (exclusão temporária)

    Sem a especificação de um ID de versão, o OSS não exclui a versão atual. Em vez disso, adiciona um marcador de exclusão como a versão mais recente. Solicitações GetObject subsequentes retornam 404 Not Found com header:x-oss-delete-marker = true e o x-oss-version-id do marcador de exclusão na resposta.

    Quando x-oss-delete-marker é verdadeiro, x-oss-version-id retorna o ID de versão do marcador de exclusão.

  • Excluir um objeto especificando um ID de versão (exclusão permanente)

    Ao especificar um ID de versão, o OSS exclui permanentemente essa versão usando o parâmetro versionId em params. Para excluir a versão com ID nulo, defina params['versionId'] = "null" em params. O OSS trata a string "null" como o ID de versão de destino.

Excluir um único objeto

Os exemplos a seguir mostram como excluir permanentemente ou temporariamente um único objeto de um bucket com versionamento.

  • Exclusão permanente

    O código de exemplo a seguir mostra como excluir permanentemente uma versão de objeto de um bucket com versionamento ao especificar o ID de versão do objeto na solicitação:

    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 version ID of the object or the delete marker. 
    var versionid = "yourObjectVersionidOrDelMarkerVersionid";
    // 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 version ID of the object or the delete marker that you want to delete. 
        var request = new DeleteObjectRequest(bucketName, objectName)
        {
            VersionId = versionid
        };
        client.DeleteObject(request);
        Console.WriteLine("Delete object succeeded");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Delete object failed. {0}", ex.Message);
    }
  • Exclusão temporária

    O código de exemplo a seguir mostra como excluir temporariamente um objeto de um bucket com versionamento ao enviar uma solicitação sem ID de versão:

    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
    {
        // Temporarily delete an object without specifying its version ID. A delete marker is added to the object. 
        var result = client.DeleteObject(bucketName, objectName);
        Console.WriteLine("Delete object succeeded, versionid: {0}, DeleteMarker: {1}", result.VersionId, result.DeleteMarker);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Delete object failed. {0}", ex.Message);
    }

Excluir vários objetos

Os exemplos a seguir descrevem como excluir permanentemente ou temporariamente vários objetos de um bucket com versionamento.

  • Exclusão permanente

    O código de exemplo a seguir mostra como excluir permanentemente vários objetos ou marcadores de exclusão com IDs de versão especificados de um bucket com versionamento:

    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
    {
        // Delete the objects with the specified version IDs or the objects whose current versions are delete markers with the specified version IDs. 
        var obj1 = new ObjectIdentifier
        {
            Key = "yourObject1Name",
            VersionId  = "yourObject1NameVersionid"
        };
    
        var obj2 = new ObjectIdentifier
        {
            Key = "yourObject2Name",
            VersionId  = "yourObject2DelMarkerVersionid"
        };
    
        IList<ObjectIdentifier> objects = new List<ObjectIdentifier>();
        objects.Add(obj1);
        objects.Add(obj2);
    
        var request = new DeleteObjectVersionsRequest(bucketName, objects);
    
        // Initiate a deleteVersions request. 
        client.DeleteObjectVersions(request);
        Console.WriteLine("DeleteObjectVersions succeeded ");
    }
    catch (OssException ex)
    {
        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
            ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
  • Exclusão temporária

    O código a seguir mostra como excluir temporariamente vários objetos sem especificar seus versionIds. É possível recuperar versões de objetos excluídas temporariamente.

    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
    {
        var keys = new List<string>();
        var listResult = client.ListObjects(bucketName);
        foreach (var summary in listResult.ObjectSummaries)
        {
            keys.Add(summary.Key);
        }
        // Specify the value of quietMode. true indicates quiet. In this mode, the deleted objects are not returned. false indicates verbose. In this mode, the deleted objects are returned. Default value: false. 
        var quietMode = false;
        // Specify the return mode by setting the value of quietMode in the DeleteObjectsRequest request. 
        var request = new DeleteObjectsRequest(bucketName, keys, quietMode);
        // Delete the objects without specifying their version IDs. Delete markers are added to the 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);
    }

Excluir objetos cujos nomes contêm um prefixo específico

O código a seguir mostra como excluir objetos com um prefixo especificado.

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";
var prefix = "yourkeyPrefix";
// 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
{   
    ObjectVersionList result = null;
    var request = new ListObjectVersionsRequest(bucketName)
    {
        // Specify the prefix that is contained in the names of the objects that you want to list. 
        Prefix = prefix;
    };

    // List the versions of all objects whose names contain the specific prefix and delete the versions. 
    do {        
        result = client.ListObjectVersions(request);
        Console.WriteLine("ListObjectVersions succeeded");
        foreach (var deleteversion in result.DeleteMarkerSummaries)
        {
            var request = new DeleteObjectRequest(bucketName, deleteversion.Key)
            {
                VersionId = deleteversion.VersionId
            };
            client.DeleteObject(request);
        }

        foreach (var objectversion in result.ObjectVersionSummaries)
        {
            var request = new DeleteObjectRequest(bucketName, objectversion.Key)
            {
                VersionId = objectversion.VersionId
            };
            client.DeleteObject(request);            
        }
        request.KeyMarker = result.NextKeyMarker;
        request.NextVersionIdMarker = result.NextVersionIdMarker ;
    } while (result.IsTruncated)
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

Referências

  • Para obter mais informações sobre a operação de API para excluir um objeto, consulte DeleteObject.

  • Para obter mais informações sobre a operação de API para excluir vários objetos, consulte DeleteMultipleObjects.