Quick start

Last Updated: Jun 05, 2017

In this chapter, you will learn how to complete some basic operations of the OSS .NET SDK.

Step 1. Initialize an OSSClient

SDK OSS operations are performed through the OSSClient class. The code below creates an OSSClient object:

  1. using Aliyun.OSS;
  2. /// <summary>
  3. /// Use the OSS access address specified by the user and the AccessKeyID and AccessKeySecret granted by Alibaba Cloud to create a new OSSClient instance.
  4. /// </summary>
  5. /// <param name="endpoint">OSS access address. </param>
  6. /// <param name="accessKeyId">OSS access ID. </param>
  7. /// <param name="accessKeySecret">OSS access password. </param>
  8. public void CreateClient(string endpoint, string accessKeyId, string accessKeySecret)
  9. {
  10. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  11. }

Note:

  • In the above code, the “accessKeyId” and “accessKeySecret” variables are allocated by the system to identify the user. They may belong to the your Alibaba Cloud account or RAM account.
  • For details about the OSSClient, see Initialization.

Step 2. Create a bucket

A bucket is a global namespace on OSS used to store objects. It is equivalent to a data container. You can create a bucket with the following code:

  1. using Aliyun.OSS;
  2. /// <summary>
  3. /// Creates a bucket on the OSS.
  4. /// </summary>
  5. /// <param name="bucketName">Name of the bucket to be created</param>
  6. public void CreateBucket(string bucketName)
  7. {
  8. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  9. try
  10. {
  11. var bucket = client.CreateBucket(bucketName);
  12. Console.WriteLine("Create bucket succeeded.");
  13. Console.WriteLine("Name:{0}", bucket.Name);
  14. }
  15. catch (Exception ex)
  16. {
  17. Console.WriteLine("Create bucket failed, {0}", ex.Message);
  18. }
  19. }

Note: For bucket naming conventions, see Bucket Management.

Step 3. Upload an object

Objects are the most basic data units on the OSS. The following code uploads an object:

  1. using Aliyun.OSS;
  2. /// <summary>
  3. /// Upload a specified object to the specified bucket on the OSS
  4. /// </summary>
  5. /// <param name="bucketName">Name of the specified bucket</param>
  6. /// <param name="key">Name of the object stored on the OSS</param>
  7. /// <param name="objectToUpload">Specify the local path of the object to be uploaded</param>
  8. public void PutObject(string bucketName, string key, string fileToUpload)
  9. {
  10. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  11. try
  12. {
  13. var result = client.PutObject(bucketName, key, fileToUpload);
  14. Console.WriteLine("Put object succeeded");
  15. Console.WriteLine("ETag:{0}", result.ETag);
  16. }
  17. catch (Exception es)
  18. {
  19. Console.WriteLine("Put object failed, {0}", ex.Message);
  20. }
  21. }

Note:

  • You can specify the associated ObjectMeta with the object for each upload object.
  • ObjectMeta consists of a series of “key-value” pairs as your description of the object.
  • To ensure consistency between the local objects and objects uploaded to the server, you can set Content-MD5.OSS will calculate and compare the MD5 value of the uploaded data with the uploaded MD5 value. If they are inconsistent, the system will return the “InvalidDigest” error code.
  • The calculated Content-MD5 value must be assigned to the ETag in ObjectMetadata during the upload process.
  • For object naming conventions and other details, see Object Uploading.

Step 4. List all objects

The following code checks objects in a bucket after you upload objects to the bucket:

  1. using Aliyun.OSS;
  2. /// <summary>
  3. /// Lists objects in the specified bucket
  4. /// </summary>
  5. /// <param name="bucketName">Name of the bucket</param>
  6. public void ListObjects(string bucketName)
  7. {
  8. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  9. try
  10. {
  11. var listObjectsRequest = new ListObjectsRequest(bucketName);
  12. var result = client.ListObjects(listObjectsRequest);
  13. Console.WriteLine("List object succeeded");
  14. foreach (var summary in result.ObjectSummaries)
  15. {
  16. Console.WriteLine(summary.Key);
  17. }
  18. }
  19. catch (Exception es)
  20. {
  21. Console.WriteLine("List object failed, {0}", ex.Message);
  22. }
  23. }

Step 5. Get a specified object

The following code retrieves an object:

  1. using Aliyun.OSS;
  2. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  3. /// <summary>
  4. // Retrieve an object from the specified bucket on OSS
  5. /// </summary>
  6. /// <param name="bucketName">Name of the bucket where the object to be retrieved is stored</param>
  7. /// <param name="key">Name of the object to be retrieved on the OSS</param>
  8. /// <param name="objectToDownload">The local directory that stores downloaded objects<param>
  9. public void GetObject(string bucketName, string key, string fileToDownload)
  10. {
  11. try
  12. {
  13. var object = client.GetObject(bucketName, key);
  14. //Download the object retrieved from the OSS to a local location
  15. using (var requestStream = object.Content)
  16. {
  17. byte[] buf = new byte[1024];
  18. using (var fs = File.Open(fileToDownload, FileMode.OpenOrCreate);
  19. {
  20. var len = 0;
  21. while ((len = requestStream.Read(buf, 0, 1024)) != 0)
  22. {
  23. fs.Write(buf, 0, len);
  24. }
  25. }
  26. }
  27. }
  28. catch (Exception es)
  29. {
  30. Console.WriteLine("Get object failed, {0}", ex.Message);
  31. }
  32. }

Note:

  • An OssObject object carrying the object information will be returned you call the OSSClient’s GetObject method.
  • With the OssObject’s GetObjectContent method, you can get the input stream of the returned object and then get the content of the object by reading the input stream. Close the stream after you finish using it.

Step 6. Delete a specified object

The following code deletes a object:

  1. using Aliyun.OSS;
  2. /// <summary>
  3. /// Delete the specified object
  4. /// </summary>
  5. /// <param name="bucketName">Name of the bucket where the object is stored</param>
  6. /// <param name="key">Name of the object to be deleted</param>
  7. public void DeleteObject(string bucketName, string key)
  8. {
  9. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  10. try
  11. {
  12. client.DeleteObject(bucketName, key);
  13. Console.WriteLine("Delete object succeeded");
  14. }
  15. catch (Exception ex)
  16. {
  17. Console.WriteLine("Delete object failed, {0}", ex.Message);
  18. }
  19. }

Example project

The following code is a complete project and demonstrates operations including creating a bucket, configuring the bucket ACL, querying the bucket ACL, uploading an object, downloading an object, querying the object list, deleting an object, and deleting a bucket.

  1. using System;
  2. using System.Collections.Generic;
  3. using Aliyun.OSS;
  4. namespace TaoYe
  5. {
  6. /// <summary>
  7. /// Example project for quick start
  8. /// </summary>
  9. public static class SimpleSamples
  10. {
  11. private const string _accessKeyId = "<your AccessKeyId>";
  12. private const string _accessKeySecret = "<your AccessKeySecret>";
  13. private const string _endpoint = "<valid host name>";
  14. private const string _bucketName = "<your bucket name>";
  15. private const string _key = "<your key>";
  16. private const string _fileToUpload = "<your local file path>";
  17. private static OssClient _client = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);
  18. public static void Main(string[] args)
  19. {
  20. CreateBucket();
  21. SetBucketAcl();
  22. GetBucketAcl();
  23. PutObject();
  24. ListObjects();
  25. GetObject();
  26. DeleteObject();
  27. // DeleteBucket();
  28. Console.WriteLine("Press any key to continue . . . ");
  29. Console.ReadKey(true);
  30. }
  31. /// <summary>
  32. /// Create a new bucket
  33. /// </summary>
  34. private static void CreateBucket()
  35. {
  36. try
  37. {
  38. var result = _client.CreateBucket(_bucketName);
  39. Console.WriteLine ("Bucket {0} is successfully created", result.Name);
  40. }
  41. catch (Exception ex)
  42. {
  43. Console.WriteLine("Failed to create the bucket. Cause: {0}", ex.Message);
  44. }
  45. }
  46. /// <summary>
  47. /// Upload a new object
  48. /// </summary>
  49. private static void PutObject()
  50. {
  51. try
  52. {
  53. _client.PutObject(_bucketName, _key, _fileToUpload);
  54. Console.WriteLine ("The object is successfully uploaded");
  55. }
  56. catch (Exception ex)
  57. {
  58. Console.WriteLine ("Failed to upload the object. Cause: {0}", ex.Message);
  59. }
  60. }
  61. /// <summary>
  62. /// List all objects in the bucket
  63. /// </summary>
  64. private static void ListObjects()
  65. {
  66. try
  67. {
  68. var keys = new List<string>();
  69. ObjectListing result = null;
  70. string nextMarker = string.Empty;
  71. /// Because a maximum of 100 objects can be returned for each ListObjects request, you need to execute ListObjects repeatedly until IsTruncated is false in the returned result.
  72. do
  73. {
  74. var listObjectsRequest = new ListObjectsRequest(_bucketName)
  75. {
  76. Marker = nextMarker,
  77. MaxKeys = 100
  78. };
  79. result = _client.ListObjects(listObjectsRequest);
  80. foreach (var summary in result.ObjectSummaries)
  81. {
  82. keys.Add(summary.Key);
  83. }
  84. nextMarker = result.NextMarker;
  85. } while (result.IsTruncated);
  86. Console.WriteLine("List objects in the bucket");
  87. foreach (var key in keys)
  88. {
  89. Console.WriteLine ("Object name: {0}", key);
  90. }
  91. }
  92. catch (Exception ex)
  93. {
  94. Console.WriteLine ("Failed to list objects in the bucket. Cause: {0}", ex.Message);
  95. }
  96. }
  97. /// <summary>
  98. /// Download an object
  99. /// </summary>
  100. private static void GetObject()
  101. {
  102. try
  103. {
  104. var result = _client.GetObject(_bucketName, _key);
  105. Console.WriteLine ("The object was downloaded successfully. Object name: {0}; object length: {1}", result.Key, result.Metadata.ContentLength);
  106. }
  107. catch (Exception ex)
  108. {
  109. Console.WriteLine ("Failed to download the object. Cause: {0}", ex.Message);
  110. }
  111. }
  112. /// <summary>
  113. /// Delete an object
  114. /// </summary>
  115. private static void DeleteObject()
  116. {
  117. try
  118. {
  119. _client.DeleteObject(_bucketName, _key);
  120. Console.WriteLine ("The object has been deleted successfully");
  121. }
  122. catch (Exception ex)
  123. {
  124. Console.WriteLine ("Failed to delete the object. Cause: {0}", ex.Message);
  125. }
  126. }
  127. /// <summary>
  128. /// Obtain the bucket ACL
  129. /// </summary>
  130. private static void GetBucketAcl()
  131. {
  132. try
  133. {
  134. var result = _client.GetBucketAcl(_bucketName);
  135. foreach (var grant in result.Grants)
  136. {
  137. Console.WriteLine ("The bucket ACL has been obtained successfully. Current permission: 0", grant.Permission.ToString());
  138. }
  139. }
  140. catch (Exception ex)
  141. {
  142. Console.WriteLine ("Failed to obtain the bucket ACL. Cause: {0}", ex.Message); {0}", ex.Message);
  143. }
  144. }
  145. /// <summary>
  146. /// Configure the bucket ACL
  147. /// </summary>
  148. private static void SetBucketAcl()
  149. {
  150. try
  151. {
  152. _client.SetBucketAcl(_bucketName, CannedAccessControlList.PublicRead);
  153. Console.WriteLine ("The bucket ACL has been configured successfully");
  154. }
  155. catch (Exception ex)
  156. {
  157. Console.WriteLine ("Failed to configure the bucket ACL. Cause: {0}", ex.Message);
  158. }
  159. }
  160. /// <summary>
  161. /// Delete a bucket
  162. /// </summary>
  163. private static void DeleteBucket()
  164. {
  165. try
  166. {
  167. _client.DeleteBucket(_bucketName);
  168. Console.WriteLine ("The bucket has been deleted successfully");
  169. }
  170. catch (Exception ex)
  171. {
  172. Console.WriteLine ("Failed to delete the bucket", ex.Message);
  173. }
  174. }
  175. }
  176. }
Thank you! We've received your feedback.