Baidu AI Cloud
中国站

百度智能云

Object Storage

Initialization

Getting Started

1.Initialize a BosClient.

BosClient is a client interacting with BOS service, and all BOS operations of BOS C# SDK are completed via BosClient.

Sample code:

  class BosClientSample 
      { 
          static void Main(string[] args) 
          { 
              const string accessKeyId =<AccessKeyID>; // Your Access Key ID 
              const string secretAccessKey =<SecretAccessKey>; // Your Secret Access Key 
              const string endpoint =<EndPoint>;          //Introduce into domain name of the region where the Bucket is. 
    
              // Initialize a BosClient 
              BceClientConfiguration config = new BceClientConfiguration(); 
              config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 
              config.Endpoint = endpoint;        
              BosClient client = new BosClient(config); 
          } 
      } 

2.Create bucket.

Bucket is a namespace on BOS. It is equivalent to a container of data and can store several data entities (objects). Before uploading data, you must create a bucket.

Sample code:

public void Createbucket(BosClient client, string bucketName) 
    { 
      // Create a bucket 
      client.Createbucket(bucketName); 
    }                            

3.Upload object.

Object is the most basic data unit in BOS. You can understand object as a file. OS provides you with four ways to upload an object: File upload, data stream upload, binary string upload and string upload.

Sample code:

public void Putobject(BosClient client, String BucketName, String ObjectKey, byte[] byte1, String string1) 
    { 
      // Access specified files. 
      FileInfo file = new FileInfo(<FilePath>);    //Designate file path. 
              
      // Upload object as file. 
      PutObjectResponse putObjectFromFileResponse = client.Putobject(BucketName, ObjectKey, file); 
             
      // Access data stream. 
      Stream inputStream = file.OpenRead(); 
              
      // Upload object as the data stream. 
      PutObjectResponse putObjectResponseFromInputStream = client.Putobject(BucketName, ObjectKey, inputStream); 
              
      // Upload object as the binary string. 
      PutObjectResponse putObjectResponseFromByte = client.Putobject(BucketName, ObjectKey, 
         Encoding.Default.GetBytes("sampledata")); 
                  
      // Upload object as the character string. 
      PutObjectResponse putObjectResponseFromString = client.Putobject(BucketName, ObjectKey, "sampledata"); 
    
      // Print ETag. 
      Console.WriteLine(putObjectFromFileResponse.ETAG); 
    } 

4.View the objects list under bucket.

After completing uploads, you can refer to the following code to view all objects under bucket.

Sample code:

public void ListObjects(BosClient client, string bucketName)
{
  // Access all object information of specified bucket
  ListObjectsResponse listObjectsResponse = client.ListObjects(bucketName);

  // Traverse all objects
  foreach (BosObjectSummary objectSummary in listObjectsResponse.Contents)
  {
    Console.WriteLine("ObjectKey: " + objectSummary.Key);
  }

}

5.Get the specified object.

You can refer to the following code to get one or more objects.

Sample code:

public void GetObject(BosClient client, String bucketName, String objectKey)
{
  // Get object and return BosObject
  BosObject bosObject = client.GetObject(bucketName, objectKey);

  // Get objectMeta
  ObjectMetadata meta = bosObject.ObjectMetadata;

  // Get the input stream of object
  Stream objectContent = bosObject.ObjectContent;

  // Process object
  ...

  // Close stream
  objectContent.Close();
}

Complete example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BaiduBce;
using BaiduBce.Auth;
using BaiduBce.Services.Bos;
using BaiduBce.Services.Bos.Model;

namespace DotnetSample
{
    internal class BaseSample
    {
        private static void Main(string[] args)
        {
            BosClient client = GenerateBosClient();
            const string bucketName = <BucektName>;    //Designate the name of the bucket
            const string objectKey = <ObjectKey>;     //Designate the name of the object

            //Creat bucket
            client.CreateBucket(bucketName);

            //Upload object
            FileInfo file = new FileInfo("d:\\lzb\\sample.txt");     //Designate path for uploaded file
            PutObjectResponse putObjectFromFileResponse = client.PutObject(bucketName, objectKey, file);
            Console.WriteLine(putObjectFromFileResponse.ETAG);

            //View Object
            ListObjectsResponse listObjectsResponse = client.ListObjects(bucketName);
            foreach (BosObjectSummary objectSummary in listObjectsResponse.Contents)
            {
                Console.WriteLine("ObjectKey: " + objectSummary.Key);
            }

            // Get Object
            BosObject bosObject = client.GetObject(bucketName, objectKey);
            // Get ObjectMeta
            ObjectMetadata meta = bosObject.ObjectMetadata;
            // Get the input stream of object
            Stream objectContent = bosObject.ObjectContent;
            // Process object
            FileStream fileStream = new FileInfo("d:\\lzb\\sampleout.txt").OpenWrite();      //Designate directory/filename for downloading files
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = objectContent.Read(buffer, 0, buffer.Length)) > 0)
            {
                fileStream.Write(buffer, 0, count);
            }

            // Close stream
            objectContent.Close();
            fileStream.Close();
            Console.WriteLine(meta.ETag);
            Console.WriteLine(meta.ContentLength);
        }

        private static BosClient GenerateBosClient()
        {
            const string accessKeyId = <AccessKeyID>; // Your Access Key ID
            const string secretAccessKey = <SecretAccessKey>; // Your Secret Access Key
            const string endpoint = <EndPoint>;        //Designate domain name of region of bucket

            // Initialize a BosClient
            BceClientConfiguration config = new BceClientConfiguration();
            config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
            config.Endpoint = endpoint;

            return new BosClient(config);
        }
    }
}

Create BOSClient

BosClient is the client of BOS service, providing methods for developers to interact with BOS service. Before using SDK to initiate a request to BOS, you need to initialize a BosClient instance and make some necessary settings to it.

  • Basic procedure

    1.Determine the EndPoint. EndPoint refers to the domain name address of EOS service in various regions, and it is Beijingbj.bcebos.com by default. 2.Create an instance of BceClientConfiguration. 3.Create DefaultBceCredentials with your AK/SK, and assign them to the Credentials attribute of BceClientConfiguration 4.Create BosClient instances with configured BceClientConfiguration.

  • Sample Code

        class BosClientSample 
        { 
            static void Main(string[] args) 
            { 
                const string accessKeyId =<AccessKeyID>; // Your Access Key ID 
                const string secretAccessKey =<SecretAccessKey>; // Your Secret Access Key 
                const string endpoint =<EndPoint>;          //Introduce into domain name of the region where the bucket is. 
          
                // Initialize a BosClient 
                BceClientConfiguration config = new BceClientConfiguration(); 
                config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 
                config.Endpoint = endpoint;        
                BosClient client = new BosClient(config); 
            } 
        } 

    EndPoint parameter can only be defined with the specified domain name of the areas included. If not specified, it defaults to the Beijing area http://bj.bcebos.com. Baidu AI Cloud currently has opened access to multi-region support, please refer to Region Selection Description.

    Currently, it supports "North China-Beijing", "South China-Guangzhou" and "East China-Suzhou". Beijing: http://bj.bcebos.com; Guangzhou: http://gz.bcebos.com; Suzhou: http://su.bcebos.com.

Configure HTTPS to Access BOS

BOS supports HTTPS, you can set EndPoint as https directly, and when EndPoint is not set, the default is http protocol.

  • Sample Code

        class BosClientSample 
        { 
            static void Main(string[] args) 
            { 
                const string accessKeyId =<AccessKeyID>; // Your Access Key ID 
                const string secretAccessKey =<SecretAccessKey>; // Your Secret Access Key 
                const string endpoint = https://bj.bcebos.com ;          //Introduce domain name of region of bucket, and set it as https protocol directly. 
          
                // Initialize a BosClient 
                BceClientConfiguration config = new BceClientConfiguration(); 
                config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 
                config.Endpoint = endpoint;        
                BosClient client = new BosClient(config); 
            } 
        } 

Configure BosClient

  • Basic procedure

    1.Create an instance of BceClientConfiguration. 2.Create DefaultBceCredentials with your AK/SK, and assign them to the Credentials attribute of BceClientConfiguration 3.Assign various attributes of BceClientConfiguratio instance. 4.Create BosClient instances with configured BceClientConfiguration.

To configure parameters of some details of BosClient, users can introduce BosClientConfiguration object when constructing BosClient. BosClientConfiguration is the configuration class of BOS service, and it can configure time-out period, maximum connections, etc. for the client.

Set network parameters

  • Sample Code

      BceClientConfiguration config = new BceClientConfiguration(); 
        
      // Set the maximum number of HTTP connections to 10.
      config.ConnectionLimit = 10; 
      
      // Set TCP connection timeout to 5,000 milliseconds 
      config.TimeoutInMillis = 5000; 
      
      // Set the timeout for reading and writing data to 50,000msec 
      config.ReadWriteTimeoutInMillis = 50000; 
  • Parameter description

    All parameters that can be specified via BceClientConfiguration are listed as follows:

Parameter Description
UserAgent User agent, referring to the HTTP User-Agent header
Protocol Connection protocol type, default-value HTTP protocol
TimeoutInMillis Timeout for establishing a connection (unit: ms), with default value of 30,000.
ReadWriteTimeoutInMillis Timeout for transmitting data over open connections (unit: ms), with default value of 30,000.
ConnectionLimit Maximum number of HTTP connections allowed to open, with default value of 5.
RetryPolicy Connection retry policy
SocketBufferSizeInBytes Socket buffer size
  • Complete example

    The following sample code demonstrates the creation and configuration of BosClient.

      using System; 
      using System.Collections.Generic; 
      using System.Linq; 
      using System.Text; 
      using BaiduBce; 
      using BaiduBce.Auth; 
      using BaiduBce.Services.Bos; 
      
      namespace DotnetSample 
      { 
        internal class BosClientSample 
          { 
              private static void Main(string[] args) 
              { 
                  const string accessKeyId =<AccessKeyID>; // Your Access Key ID 
                  const string secretAccessKey =<SecretAccessKey>; // Your Secret Access Key 
                  const string endpoint =<EndPoint>; 
      
                  // Initialize a BosClient 
                  BceClientConfiguration config = new BceClientConfiguration(); 
                  config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey); 
                  config.Endpoint = endpoint; 
      
                  // Set the maximum number of HTTP connections to 10.
                  config.ConnectionLimit = 10; 
      
                  // Set TCP connection timeout to 5,000 milliseconds 
                  config.TimeoutInMillis = 5000; 
      
                  // Set the timeout for reading and writing data to 50,000msec 
                  config.ReadWriteTimeoutInMillis = 50000; 
      
                  BosClient client = new BosClient(config); 
              } 
          } 
      }
Previous
Overview
Next
SDK Installation