列出目录下的文件和子目录
在 Prefix 和 Delimiter 结合的情况下,可以列出目录下的文件和子目录:
- using Aliyun.OSS;
- // 初始化OssClient
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- public void ListObjects(string bucketName)
- {
- try
- {
- var listObjectsRequest = new ListObjectsRequest(bucketName)
- {
- Prefix = "fun/",
- Delimiter = "/"
- };
- result = client.ListObjects(listObjectsRequest);
- Console.WriteLine("List object succeeded");
- Console.WriteLine("File:");
- foreach (var summary in result.ObjectSummaries)
- {
- Console.WriteLine("Name:{0}", summary.Key);
- }
- Console.WriteLine("Dir:");
- foreach (var prefix in result.CommonPrefixes)
- {
- Console.WriteLine("Name:{0}", prefix);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("List object failed. {0}", ex.Message);
- }
- }
输出:
- List object success
- File:
- Name:fun/test.jpg
- Dir:
- Name:fun/movie/
说明:
- 返回的结果中, ObjectSummaries 的列表中给出的是fun目录下的文件。
- 而 CommonPrefixs 的列表中给出的是fun目录下的所有子文件夹。可以看出 fun/movie/001.avi 和 fun/movie/007.avi 两个文件并没有被列出来,因为它们属于fun文件夹下的movie目录。
删除文件
删除一个文件
- using Aliyun.OSS;
- // 初始化OssClient
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- /// <summary>
- /// 列出指定存储空间下的特定文件
- /// </summary>
- /// <param name="bucketName">存储空间的名称</param>
- /// <param name="key">文件的名称</param>
- public void DeleteObject(string bucketName, string key)
- {
- try
- {
- client.DeleteObject(bucketName, key);
- Console.WriteLine("Delete object succeeded");
- }
- catch (Exception ex)
- {
- Console.WriteLine("Delete object failed. {0}", ex.Message);
- }
- }
说明: 完整代码参考
GitHub。
删除多个文件
- using Aliyun.OSS;
- // 初始化OssClient
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- /// <summary>
- /// 删除指定存储空间中的所有文件
- /// </summary>
- /// <param name="bucketName">存储空间的名称</param>
- public void DeleteObjects(string bucketName)
- {
- try
- {
- var keys = new List<string>();
- var listResult = client.ListObjects(bucketName);
- foreach (var summary in listResult.ObjectSummaries)
- {
- keys.Add(summary.Key);
- }
- var request = new DeleteObjectsRequest(bucketName, keys, false);
- client.DeleteObjects(request);
- Console.WriteLine("Delete objects succeeded");
- }
- catch (Exception ex)
- {
- Console.WriteLine("Delete objects failed. {0}", ex.Message);
- }
- }
说明: 完整代码参考
GitHub。