本节介绍如何快速使用UOS .net SDK完成常见操作,如创建存储空间、上传文件、下载文件等。
创建桶
桶相当于数据的容器,可以存储若干文件。
以下代码用于新建一个桶:
var Ak = ""; var Sk = ""; var endpoint = "http://s3.test.com"; var buckName = "xxx"; AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk, new AmazonS3Config{ ServiceURL = endpoint });
try { PutBucketResponse resp; // Construct request PutBucketRequest request = new PutBucketRequest { BucketName = buckName, }; resp = serviceClient.PutBucketAsync(request).GetAwaiter().GetResult(); Console.WriteLine(resp.HttpStatusCode); } |
上传文件
以下代码用于上传文件至UOS:
var Ak = "xxx"; var Sk = "xxx"; var endpoint = "http://s3.test.com"; AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk, new AmazonS3Config{ ServiceURL = endpoint });
try { PutObjectResponse response; PutObjectRequest putObject = new PutObjectRequest{ BucketName = "xxx", Key = "xxx" };
response = serviceClient.PutObjectAsync(putObject).GetAwaiter().GetResult(); Console.WriteLine(response.HttpStatusCode); } |
下载文件
以下代码用于获取文件的文本内容:
var Ak = "xxx"; var Sk = "xxx"; var endpoint = "http://s3.test.com"; var bucketNanme = "xxx"; var objectName = "xxx"; AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk, new AmazonS3Config{ ServiceURL = endpoint });
try { GetObjectResponse response; GetObjectRequest getObject = new GetObjectRequest{ BucketName = bucketNanme, Key = objectName };
response = serviceClient.GetObjectAsync(getObject).GetAwaiter().GetResult(); CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; response.WriteResponseStreamToFileAsync(objectName, true, token); Thread.Sleep(5000); // 等待5秒,用于上一步异步写文件 } |
列举文件
以下代码用于列举指定存储空间下的文件。
var Ak = ""; var Sk = ""; var endpoint = "http://s3-test.com"; AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk, new AmazonS3Config{ ServiceURL = endpoint });
try { ListObjectsV2Response response; ListObjectsV2Request listObjects = new ListObjectsV2Request{ BucketName = "xxx", };
response = serviceClient.ListObjectsV2Async(listObjects).GetAwaiter().GetResult(); Console.WriteLine("Object Count is {0}", response.KeyCount); Console.WriteLine("Object is:"); foreach (S3Object o_value in response.S3Objects) { Console.WriteLine(o_value.Key); } } |
删除文件
以下代码用于删除指定文件:
var Ak = "xxx"; var Sk = "xxx"; var endpoint = "http://s3.test.com"; AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk, new AmazonS3Config{ ServiceURL = endpoint });
try { DeleteObjectResponse response; DeleteObjectRequest deleteObject = new DeleteObjectRequest{ BucketName = "xxx", Key = "xxx" // object name };
response = serviceClient.DeleteObjectAsync(deleteObject).GetAwaiter().GetResult(); } |