Este tópico é um guia de início rápido para operações comuns de armazenamento com o OSS SDK for C#. Aprenda a instale o SDK, configure credenciais de acesso e execute operações básicas, como crie buckets, além de fazer upload, baixe, listar e exclua objetos.
Nota de uso
Para obter mais informações sobre os mapeamentos entre regiões do OSS e endpoints, consulte Regiões e Endpoints.
Configure credenciais
Certifique-se de ter registrado uma conta Alibaba Cloud e concluído a verificação de identidade.
-
Crie um par de AccessKey para um usuário RAM com permissões de gerenciamento do OSS.
-
Configure as variáveis de ambiente para o par de AccessKey.
Linux
-
Na interface de linha de comando, execute os comandos abaixo para adicionar as definições de variáveis de ambiente ao arquivo
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
Verifique se as variáveis de ambiente foram configuradas corretamente executando os comandos abaixo.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
No terminal, execute o comando seguinte para identificar o tipo de shell padrão.
echo $SHELL-
Realize as operações correspondentes ao tipo de shell padrão.
Zsh
-
Adicione as configurações de variáveis de ambiente ao arquivo
~/.zshrcutilizando os comandos a seguir.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Aplique as alterações executando este comando.
source ~/.zshrc -
Confirme a configuração das variáveis de ambiente com os comandos abaixo.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Utilize os comandos seguintes para anexar as definições de variáveis de ambiente ao arquivo
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Execute o comando abaixo para aplicar as mudanças.
source ~/.bash_profile -
Valide se as variáveis de ambiente estão definidas executando estes comandos.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Execute os comandos a seguir no Prompt de Comando.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Verifique a configuração das variáveis de ambiente com os comandos abaixo.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
No PowerShell, execute os comandos seguintes.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)-
Confirme se as variáveis de ambiente foram configuradas executando estes comandos.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Após modifique as variáveis de ambiente do sistema, reinicie ou atualize seu ambiente de desenvolvimento para carregar as novas variáveis. Isso inclui IDEs, interfaces de linha de comando, outros aplicativos de desktop e serviços em segundo plano.
Instale o SDK
Instalação no Windows
Instalação via NuGet
Caso o NuGet não esteja instalado no Visual Studio, instale o NuGet.
Após instalar o NuGet, crie um projeto ou abra um existente no Visual Studio e escolha .
Insira aliyun.oss.sdk na caixa de pesquisa e clique em Search. Localize Aliyun.OSS.SDK (para .NET Framework) ou Aliyun.OSS.SDK.NetCore (para .Net Core) nos resultados. Selecione a versão mais recente e clique em Install.
Instalação por referência a DLL
Baixe e descompacte o pacote do SDK para .NET.
Compile o projeto aliyun-oss-sdk no modo Release para gerar um arquivo de Dynamic Link Library (DLL).
No Visual Studio, acesse o Solution Explorer e localize seu projeto. Clique com o botão direito no nome do projeto e escolha . Na caixa de diálogo exibida, selecione Browse.
Navegue até o diretório bin gerado pelo arquivo DLL e selecione o arquivo Aliyun.OSS.dll dentro dessa pasta. Em seguida, clique em OK.
Instalação por importação de projeto
Se você baixou o pacote de instalação do SDK ou obteve o código-fonte do GitHub para realizar a instalação, siga estas etapas:
No Visual Studio, clique com o botão direito e selecione Solution no menu exibido. Escolha Add > Existing Projects.
Na caixa de diálogo que aparece, selecione o arquivo aliyun-oss-sdk.csproj e clique em Open.
Clique com o botão direito no nome do projeto e escolha . Na janela aberta, clique na aba Projects, selecione o projeto aliyun-oss-sdk e clique em OK.
Instalação no Unix/macOS
Para instalar usando o NuGet, siga estes passos:
No Xamarin, crie um novo projeto ou abra um existente. Selecione Add NuGet.
Pesquise por Aliyun.OSS.SDK ou Aliyun.OSS.SDK.NetCore. Escolha a versão mais recente e clique em Add Package para adicionar o pacote ao aplicativo do projeto.
Início rápido
Os exemplos de código a seguir demonstram como crie um bucket, além de fazer upload, baixe, listar e exclua objetos.
Criar um bucket
using Aliyun.OSS;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set yourBucketName to the name of the bucket.
var bucketName = "yourBucketName";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to v4.
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);
}
Fazer upload de um objeto
using Aliyun.OSS;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name, for example, exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project where the sample code resides.
var localFilename = "D:\\localpath\\examplefile.txt";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to v4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Upload the file.
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);
}
Baixar um objeto
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name, for example, exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Download the object to a local file named examplefile.txt and save it to the specified local path (D:\\localpath). If the specified local file exists, it is overwritten. If it does not exist, it is created.
// If you do not specify a local path, the downloaded file is saved to the local path that corresponds to the project where the sample code resides.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to v4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Download the file.
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);
}
Listar objetos
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to v4.
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 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);
}
Excluir um objeto
using Aliyun.OSS;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name, for example, exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to v4.
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);
}
Executar o código de exemplo
Crie um arquivo main.cs no diretório do seu projeto de teste. Copie o código de exemplo necessário para o arquivo main.cs.
-
Substitua yourRegion, yourBucketName e yourObjectName no comando abaixo pelos seus valores reais. Defina yourRegion como a região onde o bucket está localizado. Por exemplo, para China (Hangzhou), defina como cn-hangzhou.
dotnet script main.cs -- <yourRegion> <yourBucketName> <yourObjectName>
Referências
Para mais detalhes sobre o OSS C# SDK, consulte a documentação oficial.
Para acessar mais exemplos de código, visualize os exemplos no GitHub.

