Todos los productos
Search
Centro de documentos

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

Última actualización: Sep 22, 2026

En este tema se describe cómo eliminar un solo objeto o varios objetos a la vez.

Aviso

Los objetos eliminados no se pueden recuperar. Proceda con precaución.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization (C# SDK V1).

  • Para eliminar un objeto, debe contar con el permiso oss:DeleteObject. Para obtener más información, consulte Grant a custom policy.

Eliminar un solo objeto

A continuación se muestra el código para eliminar un objeto llamado exampleobject.txt de un bucket denominado 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);
}

Eliminar varios objetos

Puede eliminar hasta 1,000 objetos a la vez.

El resultado se devuelve en dos modos distintos. Seleccione el modo de respuesta según sus necesidades.

  • verbose: si no se especifica quietMode o se establece en false, se devuelve una lista con todos los objetos eliminados. Este es el modo predeterminado.

  • quiet: si quietMode se establece en true, no se devuelve ningún cuerpo de mensaje.

El siguiente ejemplo muestra cómo eliminar varios objetos específicos de un bucket denominado 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);
}

Referencias

  • Eliminación de un solo objeto

    Para obtener más información sobre la operación de API que permite eliminar un solo objeto, consulte DeleteObject.

  • Eliminación de varios objetos

    • Para consultar el código de ejemplo completo que elimina varios objetos, visite GitHub.

    • Para obtener más información sobre la operación de API que permite eliminar varios objetos, consulte DeleteMultipleObjects.