Initialization
Quick Start
-
Begin by initializing a BOSClient.
BosClient is the client for interacting with the BOS service, and all BOS operations in the BOS C# SDK are performed through BosClient.
Example code:
C#1class BosClientSample 2{ 3 static void Main(string[] args) 4 { 5 const string accessKeyId = <AccessKeyID>;//Your Access Key ID 6 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key 7 const string endpoint = "https://bj.bcebos.com"; //Pass in the domain name of the region where the bucket is located 8 // Initialize a BOSClient 9 BceClientConfiguration config = new BceClientConfiguration(); 10 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 11 config.Endpoint = endpoint; 12 BosClient client = new BosClient(config); 13 } 14} -
Create a bucket.
A bucket is a namespace in BOS that serves as a container for data and can hold multiple data entities (objects). You must create a bucket before uploading data.
Example code:
C#1public void CreateBucket(BosClient client, string bucketName) 2{ 3 // Create a new bucket 4 client.CreateBucket(bucketName); 5} -
Upload an object.
An object is the basic data unit in BOS. You can think of an object as a file. For simple object uploads, BOS provides four methods: file upload, data stream upload, binary string upload, and string upload.
Example code:
C#1public void PutObject(BosClient client, String bucketName, String objectKey, byte[] byte1, String string1) 2{ 3 // Get specified file 4 ileInfo file = new FileInfo(<FilePath>); //Specify the file path 5 // Upload object as a file 6 PutObjectResponse putObjectFromFileResponse = client.PutObject(bucketName, objectKey, file); 7 // Obtain data stream 8 Stream inputStream = file.OpenRead(); 9 // Upload an object in the form of a data stream 10 PutObjectResponse putObjectResponseFromInputStream = client.PutObject(bucketName, objectKey, inputStream); 11 // Upload object as binary string 12 PutObjectResponse putObjectResponseFromByte = client.PutObject(bucketName, objectKey, Encoding.Default.GetBytes("sampledata")); 13 // Upload object in string form 14 PutObjectResponse putObjectResponseFromString = client.PutObject(bucketName, objectKey, "sampledata"); 15 // Print ETag 16 Console.WriteLine(putObjectFromFileResponse.ETAG); 17} -
View the list of objects within a bucket.
Once you've finished uploading a series of files, use the following code to list all objects within the bucket.
Example code:
C#1public void ListObjects(BosClient client, string bucketName) 2{ 3 // Obtain all object information under the specified bucket 4 ListObjectsResponse listObjectsResponse = client.ListObjects(bucketName); 5 // Traverse all objects 6 foreach (BosObjectSummary objectSummary in listObjectsResponse.Contents) 7 { 8 Console.WriteLine("ObjectKey: " + objectSummary.Key); 9 } 10} -
Get the specified object.
Refer to the code below to fetch one or multiple objects.
Example code:
C#1public void GetObject(BosClient client, String bucketName, String objectKey) 2{ 3 //Obtain the object, with returned result BosObject object 4 BosObject bosObject = client.GetObject(bucketName, objectKey); 5 // Retrieve ObjectMeta 6 ObjectMetadata meta = bosObject.ObjectMetadata; 7 //Obtain the object's input stream 8 Stream objectContent = bosObject.ObjectContent; 9 // Process object 10 ... 11 // Close stream 12 objectContent.Close(); 13}
Complete example
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using System.Text;
6using BaiduBce;
7using BaiduBce.Auth;
8using BaiduBce.Services.Bos;
9using BaiduBce.Services.Bos.Model;
10namespace DotnetSample
11{
12 internal class BaseSample
13 {
14 private static void Main(string[] args)
15 {
16 BosClient client = GenerateBosClient();
17 const string bucketName = <BucketName>; //Specify bucket name
18 const string objectKey = <ObjectKey>; //Specify the object name
19 //Create Bucket
20 client.CreateBucket(bucketName);
21 //Upload Object
22 FileInfo file = new FileInfo("d:\lzb\sample.txt"); //Specify the path of the file to be uploaded
23 PutObjectResponse putObjectFromFileResponse = client.PutObject(bucketName, objectKey, file);
24 Console.WriteLine(putObjectFromFileResponse.ETAG);
25 // View Object
26 ListObjectsResponse listObjectsResponse = client.ListObjects(bucketName);
27 foreach (BosObjectSummary objectSummary in listObjectsResponse.Contents)
28 {
29 Console.WriteLine("ObjectKey: " + objectSummary.Key);
30 }
31 // Get Object
32 BosObject bosObject = client.GetObject(bucketName, objectKey);
33 // Retrieve ObjectMeta
34 ObjectMetadata meta = bosObject.ObjectMetadata;
35 //Obtain the object's input stream
36 Stream objectContent = bosObject.ObjectContent;
37 // Process object
38 FileStream fileStream = new FileInfo("d:\lzb\sampleout.txt").OpenWrite(); //Specify the directory/filename of the downloaded file
39 byte[] buffer = new byte[2048];
40 int count = 0;
41 while ((count = objectContent.Read(buffer, 0, buffer.Length)) > 0)
42 {
43 fileStream.Write(buffer, 0, count);
44 }
45 // Close stream
46 objectContent.Close();
47 fileStream.Close();
48 Console.WriteLine(meta.ETag);
49 Console.WriteLine(meta.ContentLength);
50 }
51 private static BosClient GenerateBosClient()
52 {
53 const string accessKeyId = <AccessKeyID>;//Your Access Key ID
54 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key
55 const string endpoint = "https://bj.bcebos.com"; //Specify the domain name of the region where the bucket is located
56 // Initialize a BOSClient
57 BceClientConfiguration config = new BceClientConfiguration();
58 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
59 config.Endpoint = endpoint;
60 return new BosClient(config);
61 }
62 }
63}
Create a BosClient
BosClient functions as a client for BOS services, giving developers various methods to interact with these services.
Create a BosClient with AK/SK
-
Basic workflow
- Specify the endpoint. An endpoint refers to the domain name address of the BOS service for different regions. The default domain name is set to Beijing: http://bj.bcebos.com.
- Instantiate a BceClientConfiguration object.
- Create a DefaultBceCredentials using your AK/SK credentials, then assign them to the Credentials property of BceClientConfiguration.
- Use the configured BceClientConfiguration to create a BosClient instance.
- Example code
1class BosClientSample
2{
3 static void Main(string[] args)
4 {
5 const string accessKeyId = <AccessKeyID>;//Your Access Key ID
6 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key
7 const string endpoint = "https://bj.bcebos.com"; //Pass in the domain name of the region where the bucket is located
8 // Initialize a BOSClient
9 BceClientConfiguration config = new BceClientConfiguration();
10 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
11 config.Endpoint = endpoint;
12 BosClient client = new BosClient(config);
13 }
14}
The Endpoint parameter must use region-specific domains. If unspecified, it defaults to the Beijing region http://bj.bcebos.com. Baidu AI Cloud currently supports multiple regions. Please refer to Region Selection Guide. Currently, the supported regions include "North China-Beijing," "South China-Guangzhou" and "East China-Suzhou." Beijing region: http://bj.bcebos.com, Guangzhou region: http://gz.bcebos.com, Suzhou region: http://su.bcebos.com.
Create a new BosClient with STS
-
Basic workflow
- Define the StsEndPoint. This is the domain name for the authorization service, with the default being http://sts.bj.baidubce.com.
- Instantiate a BceClientConfiguration object.
- Create a DefaultBceCredentials using your AK/SK credentials, then assign them to the Credentials property of BceClientConfiguration.
- Instantiate a StsClient object using the configured BceClientConfiguration.
- Use StsClient to request temporary AK/SK and token credentials for temporary authorization.
- Specify the endpoint. An endpoint refers to the domain name address of the BOS service for different regions. The default domain name is set to Beijing: http://bj.bcebos.com.
- Reinitialize a BceClientConfiguration object.
- Create a DefaultBceCredentials instance using temporary AK/SK and a token, then assign it to the Credentials property of the BceClientConfiguration object.
- Use the configured BceClientConfiguration to create a BosClient instance.
- Example code
1class BosClientSample
2{
3 static void Main(string[] args)
4 {
5 const string accessKeyId = <AccessKeyID>;//Your Access Key ID
6 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key
7 const string endpoint = "https://bj.bcebos.com"; //Specify the domain name of the region where the bucket is located
8 const string stsEndpoint = "http://sts.bj.baidubce.com";// Specify the BOS service domain name
9
10 //Get temporary authorization token
11 BceClientConfiguration stsConfig = new BceClientConfiguration();
12 stsConfig.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
13 stsConfig.Endpoint = stsEndpoint;
14 StsClient stsClient = new StsClient(stsConfig);
15 GetSessionTokenResponse response = stsClient.GetSessionToken();
16
17 //Initialize a BosClient using token
18 BceClientConfiguration config = new BceClientConfiguration();
19 config.Credentials = new DefaultBceSessionCredentials(
20 response.AccessKeyId,
21 response.SecretAccessKey,
22 response.SessionToken);
23 config.Endpoint = endpoint;
24 BosClient client = new BosClient(config);
25 }
26}
Note: Currently, when configuring a client using STS, regardless of the region of the corresponding bucket, the stsEndpoint must be configured as http://sts.bj.baidubce.com. However, when creating a BosClient, you still need to use the BOS endpoint, such as bj.bcebos.com, su.bcebos.com, etc.
Configure HTTPS access to BOS
BOS supports HTTPS protocol for data transmission. You can directly set the endpoint to HTTPS. If no endpoint is set, the default is HTTP.
-
Example code
PHP1class BosClientSample 2{ 3 static void Main(string[] args) 4 { 5 const string accessKeyId = <AccessKeyID>;//Your Access Key ID 6 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key 7 const string endpoint = "https://bj.bcebos.com"; //Pass in the domain name of the region where the bucket is located, and set it to https protocol 8 // Initialize a BOSClient 9 BceClientConfiguration config = new BceClientConfiguration(); 10 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 11 config.Endpoint = endpoint; 12 BosClient client = new BosClient(config); 13 } 14}
Configure custom domain name to access BOS
If you want to use a custom domain name as the endpoint to access BOS, after binding the custom domain name to a BOS bucket in the console, configure the endpoint as the custom domain name and turn on the CnameEnabled switch, such as cdn-test.cdn.bcebos.com. The configuration code is as follows:
1class BosClientSample
2{
3 static void Main(string[] args)
4 {
5 const string accessKeyId = <AccessKeyID>;//Your Access Key ID
6 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key
7 const string endpoint = <EndPoint>; // Pass in the custom domain name
8 // Initialize a BOSClient
9 BceClientConfiguration config = new BceClientConfiguration();
10 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
11 config.Endpoint = endpoint;
12 config.CnameEnabled = true;
13 BosClient client = new BosClient(config);
14 }
15}
Configure BosClient
-
Basic workflow
- Instantiate a BceClientConfiguration object.
- Create a DefaultBceCredentials using your AK/SK credentials, then assign them to the Credentials property of BceClientConfiguration.
- Set values for the various properties of the BceClientConfiguration instance.
- Use the configured BceClientConfiguration to create a BosClient instance.
If users need to configure specific parameters for the BosClient, they can provide a BosClientConfiguration object during its instantiation. BosClientConfiguration is a configuration class for the BOS service, enabling settings such as timeout duration and the maximum number of client connections.
Set network parameters
-
Example code
C#1BceClientConfiguration config = new BceClientConfiguration(); 2 // Set maximum number of HTTP connections to 10 3config.ConnectionLimit = 10; 4 // Set TCP connection timeout to 5,000 milliseconds 5config.TimeoutInMillis = 5000; 6 //Set the timeout for reading and writing data to 50,000 milliseconds 7config.ReadWriteTimeoutInMillis = 50000; -
Parameter description
The following parameters can be configured via BceClientConfiguration:
| Parameters | Description |
|---|---|
| UserAgent | User agent, refers to HTTP’s User-Agent header |
| Protocol | Connection protocol type, default value HTTP protocol |
| TimeoutInMillis | Timeout duration for establishing connections (unit: ms), with a default value of 30000 |
| ReadWriteTimeoutInMillis | Timeout duration for data transmission through the opened connections (unit: ms), with a default value of 30000 |
| ConnectionLimit | Maximum allowable HTTP connections, with a default value of 5 |
| RetryPolicy | Retry policy for connections |
| SocketBufferSizeInBytes | Buffer size for socket operations |
| CnameEnabled | Whether to use a custom domain name, the default is false. Before enabling, you need to confirm that the custom domain name has been applied for |
| PathStyleEnabled | Whether to use the third-level domain name for requests, the default is false (using the fourth-level domain name). It is enabled when some services require the use of the third-level domain name, and it is generally not recommended to set it to true |
-
Complete example
The following sample code illustrates how to create and configure a BosClient.
C#1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using BaiduBce; 6using BaiduBce.Auth; 7using BaiduBce.Services.Bos; 8namespace DotnetSample 9{ 10 internal class BosClientSample 11 { 12 private static void Main(string[] args) 13 { 14 const string accessKeyId = <AccessKeyID>;//Your Access Key ID 15 const string secretAccessKey = <SecretAccessKey>; //Your Secret Access Key 16 const string endpoint = "https://bj.bcebos.com"; 17 // Initialize a BOSClient 18 BceClientConfiguration config = new BceClientConfiguration(); 19 config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 20 config.Endpoint = endpoint; 21 // Set maximum number of HTTP connections to 10 22 config.ConnectionLimit = 10; 23 // Set TCP connection timeout to 5,000 milliseconds 24 config.TimeoutInMillis = 5000; 25 //Set the timeout for reading and writing data to 50,000 milliseconds 26 config.ReadWriteTimeoutInMillis = 50000; 27 BosClient client = new BosClient(config); 28 } 29 } 30}
