Help Center/ Object Storage Service/ SDK Reference/ .NET/ Object Download/ Performing an Asynchronous Download
Updated on 2024-12-09 GMT+08:00

Performing an Asynchronous Download

If you have any questions during the development, post them on the Issues page of GitHub. For details about parameters and usage of each API, see the API Reference.

You can call ObsClient.BeginGetObject and ObsClient.EndGetObject to download an object asynchronously.

This example downloads object objectname from bucket bucketname asynchronously.

Sample code is as follows:

// Initialize configuration parameters.
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables AccessKeyID and SecretAccessKey.
// Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// Create an instance of ObsClient.
ObsClient client = new ObsClient(accessKey, secretKey, config);
// Download an object in asynchronous mode.
try
{
    GetObjectRequest request = new GetObjectRequest()
    {
        BucketName = "bucketname",
        ObjectKey = "objectname",
    };
    client.BeginGetObject(request, delegate(IAsyncResult ar){
        try
        {
            using (GetObjectResponse response = client.EndGetObject(ar))
            {
                string dest = "savepath";
                if (!File.Exists(dest))
                {
                    // Write the data streams into the file.
                    response.WriteResponseStreamToFile(dest);
                }
                Console.WriteLine("Get object response: {0}", response.StatusCode);
             }
        }
        catch (ObsException ex)
        {
            Console.WriteLine("ErrorCode: {0}", ex.ErrorCode);
            Console.WriteLine("ErrorMessage: {0}", ex.ErrorMessage);
        }
    }, null);
    
}
catch (ObsException ex)
{
   Console.WriteLine("Message: {0}", ex.Message);
}