All Products
Search
Document Center

Object Storage Service:Download a file to a local disk (C# SDK V2)

Last Updated:Mar 20, 2026

GetObjectToFileAsync streams an OSS object directly to a local file. It doesn't load the entire object into memory, so it works for objects of any size.

The sample code uses the China (Hangzhou) region (cn-hangzhou) with a public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For region-to-endpoint mappings, see OSS regions and endpoints.

Permissions

By default, an Alibaba Cloud account has full permissions. RAM users and RAM roles have no permissions by default. Grant the required permissions through RAM Policy or Bucket Policy before running the sample code.

APIActionRequired when
GetObjectoss:GetObjectAlways
GetObjectoss:GetObjectVersionDownloading a specific object version using versionId
GetObjectkms:DecryptThe object metadata contains X-Oss-Server-Side-Encryption: KMS

Download an object to a local file

The following example downloads an object from a bucket and saves it to a local file.

using OSS = AlibabaCloud.OSS.V2;  // Alias for the OSS SDK namespace.

// Required: set the region, bucket name, object key, and local file path.
var region   = "cn-hangzhou";
var bucket   = "<your-bucket-name>";
var key      = "<your-object-key>";      // Format: folder/objectName
var filePath = "<your-local-file-path>";

// Optional: override the default endpoint for the region.
var endpoint = null as string;
// Example: "https://oss-cn-hangzhou.aliyuncs.com"

// Load default SDK configuration and read credentials from environment variables
// (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET).
var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;

if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create the OSS client.
using var client = new OSS.Client(cfg);

// Stream the object directly to the local file path.
// This avoids loading the entire object into memory.
var result = await client.GetObjectToFileAsync(new OSS.Models.GetObjectRequest()
{
    Bucket = bucket,
    Key    = key,
}, filePath);

// Print the result.
Console.WriteLine("GetObjectToFile done");
Console.WriteLine($"StatusCode: {result.StatusCode}");
Console.WriteLine($"RequestId: {result.RequestId}");
Console.WriteLine("Response headers:");
result.Headers.ToList().ForEach(x => Console.WriteLine($"{x.Key}: {x.Value}"));

Replace the following placeholders before running the code:

PlaceholderDescriptionExample
<your-bucket-name>Name of the bucket that contains the objectmy-bucket
<your-object-key>Full key of the object to downloadimages/photo.jpg
<your-local-file-path>Absolute or relative path where the file will be saved/tmp/photo.jpg

References

For the complete sample, see GetObjectToFile.cs.