通过异步方式列出文件
- using Aliyun.OSS;
- // 初始化OssClient
- static OssClient ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);
- static AutoResetEvent _event = new AutoResetEvent(false);
- public static void AsyncListObjects()
- {
- try
- {
- var listObjectsRequest = new ListObjectsRequest(bucketName);
- ossClient.BeginListObjects(listObjectsRequest, ListObjectCallback, null);
- _event.WaitOne();
- }
- catch (Exception ex)
- {
- Console.WriteLine("List objects failed. {0}", ex.Message);
- }
- }
- private static void ListObjectCallback(IAsyncResult ar)
- {
- try
- {
- var result = ossClient.EndListObjects(ar);
- foreach (var summary in result.ObjectSummaries)
- {
- Console.WriteLine("文件名称:{0}", summary.Key);
- }
- _event.Set();
- Console.WriteLine("List objects succeeded");
- }
- catch (Exception ex)
- {
- Console.WriteLine("List objects failed. {0}", ex.Message);
- }
- }
说明:
- 完整代码参考GitHub。
- 上面的ListObjectCallback方法就是异步调用结束后执行的回调方法,如果使用异步类型的接口,都需要实现类似接口。
通过ListObjectsRequest列出文件
我们可以通过设置ListObjectsRequest的参数来完成更强大的功能。比如:
- using Aliyun.OSS;
- // 初始化OssClient
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
- /// <summary>
- /// 列出指定存储空间下的文件的摘要信息OssObjectSummary列表
- /// </summary>
- /// <param name="bucketName">存储空间的名称</param>
- public void ListObjects(string bucketName)
- {
- try
- {
- var listObjectsRequest = new ListObjectsRequest(bucketName)
- {
- Delimiter = "/",
- Marker = "abc"
- };
- result = client.ListObjects(listObjectsRequest);
- Console.WriteLine("List objects succeeded");
- foreach (var summary in result.ObjectSummaries)
- {
- Console.WriteLine("文件名称:{0}", summary.Key);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("List objects failed. {0}", ex.Message);
- }
- }
可以设置的参数名称和作用如下:
说明:
- 完整代码参考GitHub。
- 如果需要遍历所有的文件,而文件数量大于100,则需要进行多次迭代。每次迭代时,将上次迭代列取最后一个文件的key作为本次迭代中的Marker即可。