O OSS SDK for C# oferece suporte a operações comuns de armazenamento no Object Storage Service (OSS). Este tópico descreve como instale o SDK, configure credenciais de acesso e execute programas de exemplo para operações básicas de bucket e objeto.
Pré-requisitos
Certifique-se de ter registrado uma conta Alibaba Cloud e concluído a verificação de identidade.
Identifique a região e o endpoint do bucket que você deseja utilizar. Para consultar os mapeamentos entre regiões e endpoints suportados pelo OSS, consulte Regions and endpoints.
Prepare um projeto C# para adicionar o SDK e execute o código de exemplo.
Etapa 1: Instale o OSS SDK for C#
Escolha o pacote compatível com o framework de destino do seu projeto: Aliyun.OSS.SDK para .NET Framework ou Aliyun.OSS.SDK.NetCore para .NET Core.
Instalação em ambiente Windows
Instalação via NuGet
Caso o NuGet não esteja instalado no Visual Studio, instale o NuGet primeiro.
Crie um projeto ou abra um existente no Visual Studio e acesse Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
Pesquise por aliyun.oss.sdk. Nos resultados, localize Aliyun.OSS.SDK ou Aliyun.OSS.SDK.NetCore, selecione a versão mais recente e clique em Install.
Instalação por referência à DLL
Baixe e descompacte o pacote do SDK para .NET no repositório do SDK no GitHub.
Compile o projeto aliyun-oss-sdk no modo Release para gerar a biblioteca DLL.
Abra o Solution Explorer no Visual Studio, selecione o projeto, clique com o botão direito no nome do projeto e escolha References > Add Reference. Na caixa de diálogo exibida, selecione Browse.
Navegue até o diretório bin onde a biblioteca DLL foi gerada, selecione o arquivo Aliyun.OSS.dll e clique em OK.
Instalação por importação de projeto
Se você já baixou o pacote do SDK ou o código-fonte do repositório do SDK no GitHub e deseja instale o SDK a partir do código-fonte, siga as etapas abaixo:
No Visual Studio, clique com o botão direito e selecione Solutions, depois clique em Add Existing Project no menu de atalho exibido.
Na caixa de diálogo aberta, selecione o arquivo aliyun-oss-sdk.csproj e clique em Open.
Clique com o botão direito no nome do projeto e escolha References > Add Reference. Na caixa de diálogo exibida, selecione a aba Project, marque o projeto aliyun-oss-sdk e clique em OK.
Instalação em ambiente Unix ou macOS
Para instale o SDK utilizando o NuGet, execute os passos a seguir:
No Xamarin, crie um projeto ou abra um existente e acesse Tools > Add NuGet Packages.
Pesquise por Aliyun.OSS.SDK ou Aliyun.OSS.SDK.NetCore, selecione a versão mais recente e clique em Add Package para adicioná-lo ao projeto.
Etapa 2: Configure credenciais de acesso
O OSS SDK for C# lê as credenciais de acesso das variáveis de ambiente OSS_ACCESS_KEY_ID e OSS_ACCESS_KEY_SECRET. Crie primeiro um par de AccessKey e, em seguida, armazene-o nessas variáveis de ambiente.
Crie um par de AccessKey de usuário RAM
Gere um par de AccessKey para um usuário RAM com permissões de gerenciamento do OSS usando um dos métodos abaixo:
Console do RAM — Para instruções detalhadas, consulte Create an AccessKey pair for a RAM user that has OSS management permissions.
Modelo ROS — Utilize um modelo do Resource Orchestration Service (ROS) para crie rapidamente um par de AccessKey para um usuário RAM com permissões de gerenciamento do OSS. Na página Create Stack do console ROS, marque a caixa de seleção em Security Confirmation e clique em Create. Após a criação da stack, copie o par de AccessKey gerado na seção Outputs.
Configure variáveis de ambiente
Utilize o par de AccessKey do usuário RAM para defina as variáveis de ambiente no sistema operacional do seu ambiente de desenvolvimento.
Linux
Execute os comandos abaixo para acrescentar as definições das 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 entraram em vigor.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
macOS
Execute o comando abaixo no terminal para identificar o tipo de shell padrão.
echo $SHELL
Configure as variáveis de ambiente conforme o tipo de shell padrão identificado.
Zsh
Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo
~/.zshrc.
echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Execute o comando abaixo para aplicar as mudanças.
source ~/.zshrc
Confirme se as variáveis de ambiente estão ativas.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Bash
Execute os comandos seguintes para inserir as definições das variáveis de ambiente no 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 este comando para efetivar as alterações.
source ~/.bash_profile
Valide se as variáveis de ambiente foram aplicadas corretamente.
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Execute os comandos abaixo no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Verifique se as variáveis de ambiente entraram em vigor.
echo %OSS_ACCESS_KEY_ID%
echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Execute os comandos a seguir no 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)
Confirme se as variáveis de ambiente estão ativas.
[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 conforme descrito acima, reinicie ou atualize seus ambientes de compilação e execução, incluindo IDE, interface de linha de comando, outros aplicativos de desktop e service em segundo plano, para garantir que as variáveis de ambiente mais recentes sejam carregadas.
Etapa 3: Execute operações básicas do OSS
Os programas de exemplo a seguir demonstram como crie um bucket, além de fazer upload, baixe, listagem e exclusão de objetos. Cada exemplo obtém credenciais de acesso das variáveis de ambiente; portanto, certifique-se de que OSS_ACCESS_KEY_ID e OSS_ACCESS_KEY_SECRET estejam configurados antes de execute qualquer programa de exemplo. Para execute um programa de exemplo:
Crie um arquivo main.cs no diretório do seu projeto de teste e copie o código de exemplo necessário para esse arquivo.
-
Substitua os espaços reservados no código de exemplo pelas suas configurações reais:
yourEndpoint: o endpoint da região onde o bucket está localizado. Para a região China (Hangzhou), o endpoint éhttps://oss-cn-hangzhou.aliyuncs.com.yourRegion: o ID da região onde o bucket está localizado, comocn-hangzhoupara a região China (Hangzhou).Nome do bucket: representado por
yourBucketNameouexamplebucketnos exemplos.Caminho completo do objeto, por exemplo
exampledir/exampleobject.txt. O caminho completo não deve incluir o nome do bucket.Caminho completo do arquivo local, como
D:\localpath\examplefile.txt. Caso nenhum caminho local seja especificado, o objeto será carregado ou baixado no caminho local do projeto ao qual o programa de exemplo pertence. Se o arquivo local especificado não existir durante um baixe, ele será criado automaticamente.
Execute o comando abaixo.
dotnet script main.cs
Crie um bucket
O código de exemplo a seguir cria um 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);
}
Se o bucket for criado com sucesso, o programa exibirá Create bucket succeeded seguido do nome do bucket.
Fazer upload de um objeto
O código de exemplo abaixo faz o upload de um arquivo local para um bucket como um objeto.
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);
}
Quando o upload do objeto for concluído, o programa exibirá Put object succeeded e o ETag do objeto.
Baixe um objeto
O código de exemplo a seguir baixa um objeto para um arquivo local.
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);
}
Se o baixe for bem-sucedido, o programa exibirá Get object succeeded e o conteúdo do objeto será gravado no arquivo local.
Listar objetos
O código de exemplo abaixo lista os objetos contidos em um 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);
}
Ao listar os objetos com sucesso, o programa exibirá o nome de cada objeto e, em seguida, List objects of bucket acompanhado do nome do bucket.
Exclua um objeto
O código de exemplo a seguir exclui um objeto de um 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);
}
Se o objeto for excluído corretamente, o programa exibirá Delete object succeeded.
Perguntas frequentes
O que fazer se o erro AccessDenied for reportado ao usar os SDKs do OSS?
Referências
Para mais informações sobre o OSS SDK for C#, visite o repositório do SDK no GitHub.
Para exemplos de código de mais recursos, consulte os exemplos no GitHub.