C# Aliyun OSS 批量删除文件

前言

最近项目测试阶段,在Aliyun OSS上存储了很多测试上传的文件,由于文件较多,即使使用Oss Brower,删起来也不方便,因此就想着写个工具,方便对OSS上的文件进行删除操作。

正文

1.新建工程,导入工具包

新建VS控制台工程,安装NuGet工具包,注意不要选错工具包,如果选择上面的Aliyun.OSS.SDK.NetCore,在调用ListBuckets等查询接口时,会报异常:“无法发送具有此谓词类型的内容正文”,具体请看我写的这篇文章C# Aliyun OSS 获取Bucket列表异常:无法发送具有此谓词类型的内容正文
C# Aliyun OSS 批量删除文件_第1张图片

2.使用建表符,使界面更加友好,任意时刻按Q/q可退出程序

using Aliyun.OSS;
using System;
using System.Collections.Generic;

//一些全局变量
private string m_DefaultEndpoint = "";
private string m_DefaultAccessKeyId = "";
private string m_DefaultAccessKeySecret = "";

private string m_Endpoint;
private string m_AccessKeyId;
private string m_AccessKeySecret;

IEnumerable<Bucket> buckets;
private string m_BucketName;

private string m_Order;

private OssClient m_OssClient;

public void Run()
{
    Console.WriteLine("┌─────────────────────────────────┐");
    Console.WriteLine("│  Ctrl+C 强制                       Press Q/q at any time to exit │");
    Console.WriteLine("│                                                                  │");
    Console.WriteLine("│                  Aliyun OSS Delete Program                       │");
    Console.WriteLine("│                                                                  │");
    Console.WriteLine($"│      EnpPoint: {m_DefaultEndpoint}              │");
    Console.WriteLine($"│      AccessKeyId: {m_DefaultAccessKeyId}                       │");
    Console.WriteLine($"│      AccessKeySecret: {m_DefaultAccessKeySecret}             │");
    Console.WriteLine("└─────────────────────────────────┘");
    Console.WriteLine("");

    Login();
}
private string GetOrder()
{
    string input = Console.ReadLine().Trim();
    if (input.Equals("Q") || input.Equals("q"))
    {
        Console.WriteLine("");
        Console.WriteLine("Press any key to close.");
        Console.ReadKey();
        Environment.Exit(0);
        return null;
    }
    else
    {
        return input;
    }

}

3.创建OssClient,并拉取Bucket列表

private void Login()
{
    while (true)
    {
        Console.Write("Use the default AK ? (Y/N): ");
        m_Order = GetOrder();
        if (m_Order.Equals("Y") || m_Order.Equals("y"))
        {
            m_Endpoint = m_DefaultEndpoint;
            m_AccessKeyId = m_DefaultAccessKeyId;
            m_AccessKeySecret = m_DefaultAccessKeySecret;
            break;
        }
        else if (m_Order.Equals("N") || m_Order.Equals("n"))
        {
            Console.Write("Please enter the Enppoint: ");
            m_Order = GetOrder();
            if (!string.IsNullOrEmpty(m_Order))
            {
                m_Endpoint = m_Order;
            }

            Console.Write("Please enter the AccessKeyId: ");
            m_Order = GetOrder();
            if (!string.IsNullOrEmpty(m_Order))
            {
                m_AccessKeyId = m_Order;
            }

            Console.Write("Please enter the AccessKeySecret: ");
            m_Order = GetOrder();
            if (!string.IsNullOrEmpty(m_Order))
            {
                m_AccessKeySecret = m_Order;
            }
            break;
        }
        else
        {
            CLog.LogLine(CLog.LogType.Error, "Input Error!");
        }
    }
    m_OssClient = new OssClient(m_Endpoint, m_AccessKeyId, m_AccessKeySecret);

    try
    {
        buckets = m_OssClient.ListBuckets();
        BucketOperation();
    }
    catch (Exception ex)
    {
        CLog.Log(CLog.LogType.Error, "Login Failed: ");
        CLog.LogLine(CLog.LogType.Error, ex.Message);

        Console.Write("重新登陆?(Y/N): ");
        m_Order = GetOrder();
        if (m_Order.Equals("Y") || m_Order.Equals("y"))
        {
            Console.Clear();
            Run();
        }
    }
}

4. 列举拉取到的Bucket列表

private void BucketOperation()
{
    Console.WriteLine("");
    Console.WriteLine("────────────── Buckets List ──────────────");
    int index = 0;
    foreach (var bucket in buckets)
    {
        CLog.Log(CLog.LogType.Log, string.Format("{0,-30}", bucket.Name));

        index++;
        if (index % 3 == 0)
        {
            CLog.Log(CLog.LogType.Log, "\r\n");
        }
        else
        {
            CLog.Log(CLog.LogType.Log, "\t");
        }
    }
    Console.WriteLine("");

    while (true)
    {
        Console.Write("Please enter the bucket's name to delete: ");
        m_Order = GetOrder();

        if (DoesBucketExist(buckets, m_Order))
        {
            m_BucketName = m_Order;
            Console.WriteLine("");
            break;
        }
        else
        {
            CLog.LogLine(CLog.LogType.Error, $"Not Found the bucket: {m_Order}");
        }
    }

    ObjectsOperation();
}
private bool DoesBucketExist(IEnumerable<Bucket> bucketList, string bucketName)
{
    foreach (var bucket in bucketList)
    {
        if (bucket.Name.Equals(bucketName))
        {
            return true;
        }
    }
    return false;
}

5. 判断要删除Bucket中的全部Object,还是某个Object

private void ObjectsOperation()
{
    while (true)
    {
        Console.Write("Delete All Objects ? (Y/N): ");
        m_Order = GetOrder();
        if (m_Order == "Y" || m_Order == "y")
        {
            DeleteAllOjbects();
            break;
        }
        else if (m_Order == "N" || m_Order == "n")
        {
            DeleteObject();
            break;
        }
        else
        {
            CLog.LogLine(CLog.LogType.Error, "Input Error!");
        }
    }
}

6. 删除Bucket中的全部Object

private void DeleteAllOjbects()
{
    Console.WriteLine("");
    Console.WriteLine("───────────── Delete Objects ──────────────");
    try
    {
        int delMaxKeys = 10;
        int delCount = 0;
        List<string> keys = new List<string>(delMaxKeys);
        while (true)
        {
            var listObjectsRequest = new ListObjectsRequest(m_BucketName)
            {
                // 默认100,最大返回1000条记录。
                MaxKeys = delMaxKeys,
            };
            var objectsList = m_OssClient.ListObjects(listObjectsRequest);

            keys.Clear();
            foreach (var summary in objectsList.ObjectSummaries)
            {
                keys.Add(summary.Key);
            }
            if (keys.Count == 0)
            {
                ClearConsoleLine(0);
                Console.WriteLine($"{delCount++} items have been deleted.");
                Console.WriteLine("All objects have been deleted.");
                break;
            }
            DeleteObjectsRequest request = new DeleteObjectsRequest(m_BucketName, keys, false);
            DeleteObjectsResult result = m_OssClient.DeleteObjects(request);

            DeleteObjectsResult.DeletedObject[] deletedKeys = result.Keys;
            int count = deletedKeys.Length;
            for (int i = 0; i < count; i++)
            {
                ClearConsoleLine(0);
                Console.Write($"{delCount++} items have been deleted. Deleting: {deletedKeys[i]}");
            }
        }
    }
    catch (Exception ex)
    {
        CLog.LogLine(CLog.LogType.Error, $"[ERROR]: {ex.Message}");
    }
}
private void ClearConsoleLine(int lineBefore)
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop - lineBefore);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, currentLineCursor - lineBefore);
}

7. 删除Bucket中的某个Object

private void DeleteObject()
{
    Console.WriteLine("");
    Console.WriteLine("───────────── Delete  Object ──────────────");

    string objectName = "";
    while (true)
    {
        Console.Write("Please enter the object's name to delete: ");
        m_Order = GetOrder();

        if (m_OssClient.DoesObjectExist(m_BucketName, m_Order))
        {
            objectName = m_Order;
            break;
        }
        else
        {
            CLog.LogLine(CLog.LogType.Error, "The object is not exist!");
        }
        m_OssClient.DeleteObject(m_BucketName, objectName);
        Console.WriteLine($"Deleted: {m_BucketName}/{objectName}");
    }
}

8. 运行测试

删除单个文件
C# Aliyun OSS 批量删除文件_第2张图片删除全部文件C# Aliyun OSS 批量删除文件_第3张图片

非常好用

点赞、收藏、+关注哦

你可能感兴趣的:(笔记,c#,阿里云,sdk)