Tous les produits
Search
Centre de documentation

Object Storage Service:Supprimer des objets (OSS SDK pour C# 1.0)

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment supprimer un objet unique, plusieurs objets et les objets dont le nom contient un préfixe spécifié dans un bucket avec versioning activé.

Notes

  • Dans cette rubrique, l'endpoint public de la région Chine (Hangzhou) est utilisé. Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région qu'OSS, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation (SDK C# V1).

  • Pour supprimer un objet, vous devez disposer de l'autorisation oss:DeleteObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Comportement de suppression dans les buckets avec versioning

Lorsque vous supprimez un objet d'un bucket avec versioning activé, vous devez décider si vous souhaitez spécifier un ID de version.

  • Supprimer un objet sans spécifier d'ID de version (suppression temporaire)

    Si vous ne spécifiez pas d'ID de version, OSS ne supprime pas la version actuelle. Il ajoute plutôt un marqueur de suppression en tant que dernière version. Les requêtes GetObject ultérieures renvoient 404 Not Found avec header:x-oss-delete-marker = true et l'x-oss-version-id du marqueur de suppression dans la réponse.

    Lorsque x-oss-delete-marker a la valeur true, x-oss-version-id renvoie l'ID de version du marqueur de suppression.

  • Supprimer un objet en spécifiant un ID de version (suppression définitive)

    Si vous spécifiez un ID de version, OSS supprime définitivement cette version à l'aide du paramètre versionId dans params. Pour supprimer la version dont l'ID est null, définissez params['versionId'] = "null" dans params. OSS traite la chaîne « null » comme l'ID de version cible.

Supprimer un objet unique

Les exemples suivants montrent comment supprimer définitivement ou temporairement un objet unique d'un bucket avec versioning activé.

  • Suppression définitive

    L'exemple de code suivant montre comment supprimer définitivement une version d'objet d'un bucket avec versioning activé en spécifiant l'ID de version de l'objet dans la requête :

    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);
    }
  • Suppression temporaire

    L'exemple de code suivant montre comment supprimer temporairement un objet d'un bucket avec versioning activé en envoyant une requête sans spécifier d'ID de version :

    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);
    }

Supprimer plusieurs objets

Les exemples suivants décrivent comment supprimer définitivement ou temporairement plusieurs objets d'un bucket avec versioning activé.

  • Suppression définitive

    L'exemple de code suivant montre comment supprimer définitivement plusieurs objets ou marqueurs de suppression dotés d'IDs de version spécifiés dans un bucket avec versioning activé :

    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);
    }
  • Suppression temporaire

    Le code suivant montre comment supprimer temporairement plusieurs objets sans spécifier leurs versionIds. Les versions d'objets supprimées temporairement peuvent être récupérées.

    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);
    }

Supprimer des objets dont le nom contient un préfixe spécifique

Le code suivant montre comment supprimer des fichiers avec un préfixe spécifié.

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);
}

Références

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour supprimer un objet, consultez DeleteObject.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour supprimer plusieurs objets, consultez DeleteMultipleObjects.