OSS SDK for C# supports common storage operations in Object Storage Service (OSS). This topic describes how to install the SDK, configure access credentials, and run sample programs for basic bucket and object operations.
Prerequisites
Make sure that you have registered an Alibaba Cloud account and completed identity verification.
Determine the region and the endpoint of the bucket that you want to use. For the mappings between the regions and endpoints supported by OSS, see Regions and endpoints.
Prepare a C# project in which you can add the SDK and run the sample code.
Step 1: Install OSS SDK for C#
Choose the package that matches the target framework of your project: Aliyun.OSS.SDK for .NET Framework, or Aliyun.OSS.SDK.NetCore for .NET Core.
Install in a Windows environment
Install by using NuGet
If NuGet is not installed in your Visual Studio, install NuGet first.
Create a project or open an existing project in Visual Studio, and choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
Search for aliyun.oss.sdk. In the results, find Aliyun.OSS.SDK or Aliyun.OSS.SDK.NetCore, select the latest version, and click Install.
Install by referencing the DLL
Download and decompress the .NET SDK package from the SDK repository on GitHub.
Compile the aliyun-oss-sdk project in Release mode to generate a DLL library.
Open Solution Explorer in Visual Studio, select your project, right-click the project name, and choose References > Add Reference. In the dialog box that appears, select Browse.
Go to the bin directory in which the DLL library is generated, select the Aliyun.OSS.dll file, and click OK.
Install by importing the project
If you have downloaded the SDK package or the source code from the SDK repository on GitHub and want to install the SDK from the source code, perform the following steps:
In Visual Studio, right-click and select Solutions, and then click Add Existing Project on the shortcut menu that appears.
In the dialog box that appears, select the aliyun-oss-sdk.csproj file and click Open.
Right-click the project name and choose References > Add Reference. In the dialog box that appears, select the Project tab, select the aliyun-oss-sdk project, and click OK.
Install in a Unix or macOS environment
To install the SDK by using NuGet, perform the following steps:
In Xamarin, create a project or open an existing project, and choose Tools > Add NuGet Packages.
Search for Aliyun.OSS.SDK or Aliyun.OSS.SDK.NetCore, select the latest version, and click Add Package to add it to your project.
Step 2: Configure access credentials
OSS SDK for C# reads access credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. Create an AccessKey pair first, and then store the AccessKey pair in these environment variables.
Create a RAM user AccessKey pair
Create an AccessKey pair for a RAM user that has OSS management permissions by using one of the following methods:
RAM console — For instructions, see Create an AccessKey pair for a RAM user that has OSS management permissions.
ROS template — Use a Resource Orchestration Service (ROS) template to quickly create an AccessKey pair for a RAM user that has OSS management permissions. On the Create Stack page of the ROS console, select the check box under Security Confirmation, and then click Create. After the stack is created, copy the created AccessKey pair from Outputs.
Configure environment variables
Use the AccessKey pair of the RAM user to configure environment variables on the operating system of your development environment.
Linux
Run the following commands to append the environment variable settings to the
~/.bashrcfile.
echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrcRun the following command to apply the changes.
source ~/.bashrcVerify that the environment variables take effect.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRETmacOS
Run the following command in the terminal to view the default shell type.
echo $SHELLConfigure the environment variables based on the default shell type.
Zsh
Run the following commands to append the environment variable settings to the
~/.zshrcfile.
echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrcRun the following command to apply the changes.
source ~/.zshrcVerify that the environment variables take effect.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRETBash
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.
echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profileRun the following command to apply the changes.
source ~/.bash_profileVerify that the environment variables take effect.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRETWindows
CMD
Run the following commands in CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"Verify that the environment variables take effect.
echo %OSS_ACCESS_KEY_ID%
echo %OSS_ACCESS_KEY_SECRET%PowerShell
Run the following commands in PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)Verify that the environment variables take effect.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)After you modify the system environment variables as described above, restart or refresh your build and runtime environments, including your IDE, command-line interface, other desktop applications, and background services, to make sure that the latest system environment variables are loaded.
Step 3: Perform basic OSS operations
The following sample programs show how to create a bucket and upload, download, list, and delete objects. Each sample obtains access credentials from environment variables, so make sure that OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are configured before you run a sample program. To run a sample program:
Create a main.cs file in your test project directory and copy the required sample code into the main.cs file.
Replace the placeholders in the sample code with your actual configurations:
yourEndpoint: the endpoint of the region in which the bucket is located. For the China (Hangzhou) region, the endpoint ishttps://oss-cn-hangzhou.aliyuncs.com.yourRegion: the ID of the region in which the bucket is located, such ascn-hangzhoufor the China (Hangzhou) region.The bucket name:
yourBucketNameorexamplebucketin the samples.The full path of the object, such as
exampledir/exampleobject.txt. The full path cannot contain the bucket name.The full path of the local file, such as
D:\localpath\examplefile.txt. If you do not specify a local path, the object is uploaded from or downloaded to the local path of the project to which the sample program belongs. If the specified local file does not exist during a download, the file is created.
Run the following command.
dotnet script main.csCreate a bucket
The following sample code creates a bucket.
using Aliyun.OSS;
// Set yourEndpoint to the endpoint of the region in which the bucket is located.
var endpoint = "yourEndpoint";
// Set yourRegion to the ID of the region in which the bucket is located.
var region = "yourRegion";
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "yourBucketName";
// Create a ClientConfiguration instance and modify the default parameters as required.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Create a bucket.
var bucket = client.CreateBucket(bucketName);
Console.WriteLine("Create bucket succeeded, {0} ", bucket.Name);
}
catch (Exception ex)
{
Console.WriteLine("Create bucket failed, {0}", ex.Message);
}If the bucket is created, the program prints Create bucket succeeded and the name of the bucket.
Upload an object
The following sample code uploads a local file to a bucket as an object.
using Aliyun.OSS;
// Set yourEndpoint to the endpoint of the region in which the bucket is located.
var endpoint = "yourEndpoint";
// Set yourRegion to the ID of the region in which the bucket is located.
var region = "yourRegion";
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Specify the full path of the object, which cannot contain the bucket name.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file to upload.
var localFilename = "D:\\localpath\\examplefile.txt";
// Create a ClientConfiguration instance and modify the default parameters as required.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Upload the object.
var result = client.PutObject(bucketName, objectName, localFilename);
Console.WriteLine("Put object succeeded, ETag: {0} ", result.ETag);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}If the object is uploaded, the program prints Put object succeeded and the ETag of the object.
Download an object
The following sample code downloads an object to a local file.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the endpoint of the region in which the bucket is located.
var endpoint = "yourEndpoint";
// Set yourRegion to the ID of the region in which the bucket is located.
var region = "yourRegion";
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Specify the full path of the object, which cannot contain the bucket name.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file to which the object is downloaded.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create a ClientConfiguration instance and modify the default parameters as required.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Download the object.
var result = client.GetObject(bucketName, objectName);
using (var requestStream = result.Content)
{
using (var fs = File.Open(downloadFilename, FileMode.OpenOrCreate))
{
int length = 4 * 1024;
var buf = new byte[length];
do
{
length = requestStream.Read(buf, 0, length);
fs.Write(buf, 0, length);
} while (length != 0);
}
}
Console.WriteLine("Get object succeeded");
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}If the object is downloaded, the program prints Get object succeeded and the object content is written to the local file.
List objects
The following sample code lists the objects in a bucket.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the endpoint of the region in which the bucket is located.
var endpoint = "yourEndpoint";
// Set yourRegion to the ID of the region in which the bucket is located.
var region = "yourRegion";
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Create a ClientConfiguration instance and modify the default parameters as required.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var objects = new List<string>();
ObjectListing result = null;
string nextMarker = string.Empty;
do
{
var listObjectsRequest = new ListObjectsRequest(bucketName)
{
Marker = nextMarker,
};
// List the objects.
result = client.ListObjects(listObjectsRequest);
foreach (var summary in result.ObjectSummaries)
{
Console.WriteLine(summary.Key);
objects.Add(summary.Key);
}
nextMarker = result.NextMarker;
} while (result.IsTruncated);
Console.WriteLine("List objects of bucket:{0} succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}If the objects are listed, the program prints the name of each object and then List objects of bucket with the bucket name.
Delete an object
The following sample code deletes an object from a bucket.
using Aliyun.OSS;
// Set yourEndpoint to the endpoint of the region in which the bucket is located.
var endpoint = "yourEndpoint";
// Set yourRegion to the ID of the region in which the bucket is located.
var region = "yourRegion";
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Specify the full path of the object, which cannot contain the bucket name.
var objectName = "exampledir/exampleobject.txt";
// Create a ClientConfiguration instance and modify the default parameters as required.
var conf = new ClientConfiguration();
// Specify the V4 signature algorithm.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Delete the object.
client.DeleteObject(bucketName, objectName);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete object failed, {0}", ex.Message);
}If the object is deleted, the program prints Delete object succeeded.
FAQ
What do I do if the AccessDenied error is reported when using OSS SDKs?
References
For more information about OSS SDK for C#, see the SDK repository on GitHub.
For code examples of more features, see GitHub samples.