Esta página é somente para clientes atuais do serviço Amazon Glacier que usam Vaults e a API REST original de 2012.
Se você estiver procurando por soluções de armazenamento de arquivos, recomendamos usar as classes de armazenamento Amazon Glacier no Amazon S3, S3 Glacier Instant Retrieval, S3 Glacier Flexible Retrieval e S3 Glacier Deep Archive. Para saber mais sobre essas opções de armazenamento, consulte as classes de armazenamento do Amazon Glacier
O Amazon Glacier (serviço autônomo original baseado em cofre) não aceitará mais novos clientes a partir de 15 de dezembro de 2025, sem impacto para os clientes existentes. O Amazon Glacier é um serviço independente APIs que armazena dados em cofres e é diferente das classes de armazenamento Amazon S3 e Amazon S3 Glacier. Seus dados existentes permanecerão seguros e acessíveis no Amazon Glacier indefinidamente. Nenhuma migração é necessária. Para armazenamento de arquivamento de baixo custo e longo prazo, AWS recomenda as classes de armazenamento Amazon S3 Glacier
As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Baixando um arquivo no Amazon Glacier usando o AWS SDK para .NET
Tanto o alto quanto o baixo nível APIs fornecidos pelo Amazon SDK para .NET fornecem um método para baixar um arquivo.
Tópicos
Baixando um arquivo usando a API de alto nível do AWS SDK para .NET
A classe ArchiveTransferManager da API de nível superior fornece o método Download que você pode usar para fazer download de um arquivo.
Importante
A classe ArchiveTransferManager cria um tópico do Amazon Simple Notification Service (Amazon SNS) e uma fila do Amazon Simple Queue Service (Amazon SQS) que está inscrita nesse tópico. Em seguida, ela inicia o trabalho de recuperação do arquivo e sonda a fila em busca do arquivo disponível. Assim que o arquivo estiver disponível, o download começará. Para obter informações sobre tempos de recuperação, consulte Opções de recuperação de arquivos
Exemplo: Baixar um arquivo usando a API de alto nível do AWS SDK para .NET
O exemplo de código C# a seguir faz download de um arquivo de um cofre (examplevault) na região Oeste dos EUA (Oregon).
Para step-by-step obter instruções sobre como executar esse exemplo, consulteExecutar exemplos de código. Você precisa atualizar o código conforme mostrado com um ID de arquivo existente e o caminho do arquivo local onde deseja salvar o arquivo obtido por download.
using System; using Amazon.Glacier; using Amazon.Glacier.Transfer; using Amazon.Runtime; namespace glacier.amazon.com.rproxy.govskope.ca.docsamples { class ArchiveDownloadHighLevel { static string vaultName = "examplevault"; static string archiveId = "*** Provide archive ID ***"; static string downloadFilePath = "*** Provide the file name and path to where to store the download ***"; public static void Main(string[] args) { try { var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2); var options = new DownloadOptions(); options.StreamTransferProgress += ArchiveDownloadHighLevel.progress; // Download an archive. Console.WriteLine("Intiating the archive retrieval job and then polling SQS queue for the archive to be available."); Console.WriteLine("Once the archive is available, downloading will begin."); manager.Download(vaultName, archiveId, downloadFilePath, options); Console.WriteLine("To continue, press Enter"); Console.ReadKey(); } catch (AmazonGlacierException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("To continue, press Enter"); Console.ReadKey(); } static int currentPercentage = -1; static void progress(object sender, StreamTransferProgressArgs args) { if (args.PercentDone != currentPercentage) { currentPercentage = args.PercentDone; Console.WriteLine("Downloaded {0}%", args.PercentDone); } } } }
Baixando um arquivo usando a API de baixo nível do AWS SDK para .NET
A seguir estão as etapas para baixar um arquivo do Amazon Glacier (Amazon Glacier) usando a API de baixo nível do. AWS SDK para .NET
-
Crie uma instância da classe
AmazonGlacierClient(o cliente).Você precisa especificar uma AWS região de onde deseja baixar o arquivo. Todas as operações que você executa usando esse cliente se aplicam a essa AWS região.
-
Inicie um trabalho
archive-retrievalexecutando o métodoInitiateJob.Você fornece informações do trabalho, como o ID do arquivo que deseja baixar e o tópico opcional do Amazon SNS no qual deseja que o Amazon Glacier publique uma mensagem de conclusão do trabalho, criando uma instância da classe.
InitiateJobRequestO Amazon Glacier retorna uma ID de trabalho em resposta. A resposta está disponível em uma instância da classeInitiateJobResponse.AmazonGlacierClient client; client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2); InitiateJobRequest initJobRequest = new InitiateJobRequest() { VaultName = vaultName, JobParameters = new JobParameters() { Type = "archive-retrieval", ArchiveId = "*** Provide archive id ***", SNSTopic = "*** Provide Amazon SNS topic ARN ***", } }; InitiateJobResponse initJobResponse = client.InitiateJob(initJobRequest); string jobId = initJobResponse.JobId;Opcionalmente, você pode especificar um intervalo de bytes para solicitar que o Amazon Glacier prepare somente uma parte do arquivamento, conforme mostrado na solicitação a seguir. A solicitação especifica que o Amazon Glacier prepare somente a parte de 1 MB a 2 MB do arquivo.
AmazonGlacierClient client; client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2); InitiateJobRequest initJobRequest = new InitiateJobRequest() { VaultName = vaultName, JobParameters = new JobParameters() { Type = "archive-retrieval", ArchiveId = "*** Provide archive id ***", SNSTopic = "*** Provide Amazon SNS topic ARN ***", } }; // Specify byte range. int ONE_MEG = 1048576; initJobRequest.JobParameters.RetrievalByteRange = string.Format("{0}-{1}", ONE_MEG, 2 * ONE_MEG -1); InitiateJobResponse initJobResponse = client.InitiateJob(initJobRequest); string jobId = initJobResponse.JobId; -
Aguarde a conclusão do trabalho .
Você deve aguardar até a saída do trabalho estar pronta para download. Se você definiu uma configuração de notificação no cofre identificando um tópico do Amazon Simple Notification Service (Amazon SNS) ou especificou um tópico do Amazon SNS ao iniciar um trabalho, o Amazon Glacier enviará uma mensagem para esse tópico após concluir o trabalho. O exemplo de código fornecido na seção a seguir usa o Amazon SNS para o Amazon Glacier para publicar uma mensagem.
Você também pode pesquisar o Amazon Glacier chamando
DescribeJobo método para determinar o status de conclusão do trabalho. Apesar disso, usar um tópico do Amazon SNS para notificação é a abordagem recomendada. -
Faça download da saída do trabalho (dados de arquivo) executando o método
GetJobOutput.Você fornece as informações da solicitação, como o ID de trabalho e o nome do cofre, criando uma instância da classe
GetJobOutputRequest. A saída que o Amazon Glacier retorna está disponível noGetJobOutputResponseobjeto.GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest() { JobId = jobId, VaultName = vaultName }; GetJobOutputResponse getJobOutputResponse = client.GetJobOutput(getJobOutputRequest); using (Stream webStream = getJobOutputResponse.Body) { using (Stream fileToSave = File.OpenWrite(fileName)) { CopyStream(webStream, fileToSave); } }O trecho de código anterior faz download de toda a saída do trabalho. Opcionalmente, você pode recuperar somente uma parte da saída ou fazer download de toda a saída em blocos menores especificando o intervalo de bytes em
GetJobOutputRequest.GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest() { JobId = jobId, VaultName = vaultName }; getJobOutputRequest.SetRange(0, 1048575); // Download only the first 1 MB chunk of the output.Em resposta à sua
GetJobOutputchamada, o Amazon Glacier retorna a soma de verificação da parte dos dados que você baixou, se determinadas condições forem atendidas. Para obter mais informações, consulte Receber somas de verificação durante o download de dados.Para verificar se não há erros no download, você pode então calcular a soma de verificação no lado do cliente e compará-la com a soma de verificação que o Amazon Glacier enviou na resposta.
Para um trabalho de recuperação de arquivamento com o intervalo opcional especificado, quando você obtém a descrição do trabalho, ela inclui a soma de verificação do intervalo que você está recuperando (SHA256TreeHash). Você pode usar esse valor para verificar ainda mais a precisão de todo o intervalo de bytes que você baixará posteriormente. Por exemplo, se iniciar um trabalho para recuperar um intervalo alinhado ao hash de árvore e fizer download de saída em blocos, de maneira que cada uma das solicitações
GetJobOutputretorne uma soma de verificação, você poderá computar a soma de verificação de cada parte cujo download você faz no lado do cliente e o hash de árvore. Você pode compará-la com a soma de verificação que o Amazon Glacier retorna em resposta à sua solicitação de trabalho descrita para verificar se toda a faixa de bytes que você baixou é a mesma que a faixa de bytes armazenada no Amazon Glacier.Para obter um exemplo funcional, consulte Exemplo 2: Recuperação de um arquivamento usando a API de baixo nível da saída AWS SDK para .NET—Download em partes.
Exemplo 1: Recuperação de um arquivamento usando a API de baixo nível do AWS SDK para .NET
O exemplo de código do C# a seguir faz download de um arquivo do cofre especificado. Depois que o trabalho for concluído, o exemplo fará download de toda a saída em uma única chamada GetJobOutput. Para obter um exemplo de como fazer download de saída em blocos, consulte Exemplo 2: Recuperação de um arquivamento usando a API de baixo nível da saída AWS SDK para .NET—Download em partes.
O exemplo realiza as seguintes tarefas:
-
Configure o tópico do Amazon Simple Notification Service (Amazon SNS)
O Amazon Glacier envia uma notificação para esse tópico após concluir o trabalho.
Configure a Fila do Amazon Simple Queue Service (Amazon SQS)
O exemplo anexa uma política à fila para permitir que o tópico do Amazon SNS publique mensagens.
Inicia um trabalho para fazer download do arquivo especificado.
Na solicitação de trabalho, o exemplo especifica o tópico do Amazon SNS para que o Amazon Glacier possa enviar uma mensagem após concluir o trabalho.
Verifica periodicamente a fila do Amazon SQS em busca de uma mensagem.
Se houver uma mensagem, analise o JSON e verifique se o trabalho foi concluído com êxito. Se for o caso, faça download do arquivo. O exemplo de código usa a biblioteca do JSON.NET (consulte JSON.NET
) para analisar o JSON. Limpa excluindo o tópico do Amazon SNS e a fila do Amazon SQS criada por ele.
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Amazon.Glacier; using Amazon.Glacier.Model; using Amazon.Runtime; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.SQS; using Amazon.SQS.Model; using Newtonsoft.Json; namespace glacier.amazon.com.rproxy.govskope.ca.docsamples { class ArchiveDownloadLowLevelUsingSNSSQS { static string topicArn; static string queueUrl; static string queueArn; static string vaultName = "*** Provide vault name ***"; static string archiveID = "*** Provide archive ID ***"; static string fileName = "*** Provide the file name and path to where to store downloaded archive ***"; static AmazonSimpleNotificationServiceClient snsClient; static AmazonSQSClient sqsClient; const string SQS_POLICY = "{" + " \"Version\" : \"2012-10-17\",&TCX5-2025-waiver;" + " \"Statement\" : [" + " {" + " \"Sid\" : \"sns-rule\"," + " \"Effect\" : \"Allow\"," + " \"Principal\" : {\"Service\" : \"sns.amazonaws.com\" }," + " \"Action\" : \"sqs:SendMessage\"," + " \"Resource\" : \"{QueueArn}\"," + " \"Condition\" : {" + " \"ArnLike\" : {" + " \"aws:SourceArn\" : \"{TopicArn}\"" + " }" + " }" + " }" + " ]" + "}"; public static void Main(string[] args) { AmazonGlacierClient client; try { using (client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2)) { Console.WriteLine("Setup SNS topic and SQS queue."); SetupTopicAndQueue(); Console.WriteLine("To continue, press Enter"); Console.ReadKey(); Console.WriteLine("Retrieving..."); RetrieveArchive(client); } Console.WriteLine("Operations successful. To continue, press Enter"); Console.ReadKey(); } catch (AmazonGlacierException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } finally { // Delete SNS topic and SQS queue. snsClient.DeleteTopic(new DeleteTopicRequest() { TopicArn = topicArn }); sqsClient.DeleteQueue(new DeleteQueueRequest() { QueueUrl = queueUrl }); } } static void SetupTopicAndQueue() { snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USWest2); sqsClient = new AmazonSQSClient(Amazon.RegionEndpoint.USWest2); long ticks = DateTime.Now.Ticks; topicArn = snsClient.CreateTopic(new CreateTopicRequest { Name = "GlacierDownload-" + ticks }).TopicArn; Console.Write("topicArn: "); Console.WriteLine(topicArn); CreateQueueRequest createQueueRequest = new CreateQueueRequest(); createQueueRequest.QueueName = "GlacierDownload-" + ticks; CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest); queueUrl = createQueueResponse.QueueUrl; Console.Write("QueueURL: "); Console.WriteLine(queueUrl); GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(); getQueueAttributesRequest.AttributeNames = new List<string> { "QueueArn" }; getQueueAttributesRequest.QueueUrl = queueUrl; GetQueueAttributesResponse response = sqsClient.GetQueueAttributes(getQueueAttributesRequest); queueArn = response.QueueARN; Console.Write("QueueArn: "); Console.WriteLine(queueArn); // Setup the Amazon SNS topic to publish to the SQS queue. snsClient.Subscribe(new SubscribeRequest() { Protocol = "sqs", Endpoint = queueArn, TopicArn = topicArn }); // Add policy to the queue so SNS can send messages to the queue. var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QueueArn}", queueArn); sqsClient.SetQueueAttributes(new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string> { { QueueAttributeName.Policy, policy } } }); } static void RetrieveArchive(AmazonGlacierClient client) { // Initiate job. InitiateJobRequest initJobRequest = new InitiateJobRequest() { VaultName = vaultName, JobParameters = new JobParameters() { Type = "archive-retrieval", ArchiveId = archiveID, Description = "This job is to download archive.", SNSTopic = topicArn, } }; InitiateJobResponse initJobResponse = client.InitiateJob(initJobRequest); string jobId = initJobResponse.JobId; // Check queue for a message and if job completed successfully, download archive. ProcessQueue(jobId, client); } private static void ProcessQueue(string jobId, AmazonGlacierClient client) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = 1 }; bool jobDone = false; while (!jobDone) { Console.WriteLine("Poll SQS queue"); ReceiveMessageResponse receiveMessageResponse = sqsClient.ReceiveMessage(receiveMessageRequest); if (receiveMessageResponse.Messages.Count == 0) { Thread.Sleep(10000 * 60); continue; } Console.WriteLine("Got message"); Message message = receiveMessageResponse.Messages[0]; Dictionary<string, string> outerLayer = JsonConvert.DeserializeObject<Dictionary<string, string>>(message.Body); Dictionary<string, object> fields = JsonConvert.DeserializeObject<Dictionary<string, object>>(outerLayer["Message"]); string statusCode = fields["StatusCode"] as string; if (string.Equals(statusCode, GlacierUtils.JOB_STATUS_SUCCEEDED, StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Downloading job output"); DownloadOutput(jobId, client); // Save job output to the specified file location. } else if (string.Equals(statusCode, GlacierUtils.JOB_STATUS_FAILED, StringComparison.InvariantCultureIgnoreCase)) Console.WriteLine("Job failed... cannot download the archive."); jobDone = true; sqsClient.DeleteMessage(new DeleteMessageRequest() { QueueUrl = queueUrl, ReceiptHandle = message.ReceiptHandle }); } } private static void DownloadOutput(string jobId, AmazonGlacierClient client) { GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest() { JobId = jobId, VaultName = vaultName }; GetJobOutputResponse getJobOutputResponse = client.GetJobOutput(getJobOutputRequest); using (Stream webStream = getJobOutputResponse.Body) { using (Stream fileToSave = File.OpenWrite(fileName)) { CopyStream(webStream, fileToSave); } } } public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[65536]; int length; while ((length = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, length); } } } }
Exemplo 2: Recuperação de um arquivamento usando a API de baixo nível da saída AWS SDK para .NET—Download em partes
O exemplo de código C# a seguir recupera um arquivo do Amazon Glacier. O exemplo de código faz download da saída do trabalho em blocos especificando o intervalo de bytes em um objeto GetJobOutputRequest.
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Amazon.Glacier; using Amazon.Glacier.Model; using Amazon.Glacier.Transfer; using Amazon.Runtime; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.SQS; using Amazon.SQS.Model; using Newtonsoft.Json; using System.Collections.Specialized; namespace glacier.amazon.com.rproxy.govskope.ca.docsamples { class ArchiveDownloadLowLevelUsingSQLSNSOutputUsingRange { static string topicArn; static string queueUrl; static string queueArn; static string vaultName = "*** Provide vault name ***"; static string archiveId = "*** Provide archive ID ***"; static string fileName = "*** Provide the file name and path to where to store downloaded archive ***"; static AmazonSimpleNotificationServiceClient snsClient; static AmazonSQSClient sqsClient; const string SQS_POLICY = "{" + " \"Version\" : \"2012-10-17\",&TCX5-2025-waiver;" + " \"Statement\" : [" + " {" + " \"Sid\" : \"sns-rule\"," + " \"Effect\" : \"Allow\"," + " \"Principal\" : {\"AWS\" : \"arn:aws:iam::123456789012:root\" }," + " \"Action\" : \"sqs:SendMessage\"," + " \"Resource\" : \"{QuernArn}\"," + " \"Condition\" : {" + " \"ArnLike\" : {" + " \"aws:SourceArn\" : \"{TopicArn}\"" + " }" + " }" + " }" + " ]" + "}"; public static void Main(string[] args) { AmazonGlacierClient client; try { using (client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2)) { Console.WriteLine("Setup SNS topic and SQS queue."); SetupTopicAndQueue(); Console.WriteLine("To continue, press Enter"); Console.ReadKey(); Console.WriteLine("Download archive"); DownloadAnArchive(archiveId, client); } Console.WriteLine("Operations successful. To continue, press Enter"); Console.ReadKey(); } catch (AmazonGlacierException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } finally { // Delete SNS topic and SQS queue. snsClient.DeleteTopic(new DeleteTopicRequest() { TopicArn = topicArn }); sqsClient.DeleteQueue(new DeleteQueueRequest() { QueueUrl = queueUrl }); } } static void SetupTopicAndQueue() { long ticks = DateTime.Now.Ticks; // Setup SNS topic. snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USWest2); sqsClient = new AmazonSQSClient(Amazon.RegionEndpoint.USWest2); topicArn = snsClient.CreateTopic(new CreateTopicRequest { Name = "GlacierDownload-" + ticks }).TopicArn; Console.Write("topicArn: "); Console.WriteLine(topicArn); CreateQueueRequest createQueueRequest = new CreateQueueRequest(); createQueueRequest.QueueName = "GlacierDownload-" + ticks; CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest); queueUrl = createQueueResponse.QueueUrl; Console.Write("QueueURL: "); Console.WriteLine(queueUrl); GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(); getQueueAttributesRequest.AttributeNames = new List<string> { "QueueArn" }; getQueueAttributesRequest.QueueUrl = queueUrl; GetQueueAttributesResponse response = sqsClient.GetQueueAttributes(getQueueAttributesRequest); queueArn = response.QueueARN; Console.Write("QueueArn: "); Console.WriteLine(queueArn); // Setup the Amazon SNS topic to publish to the SQS queue. snsClient.Subscribe(new SubscribeRequest() { Protocol = "sqs", Endpoint = queueArn, TopicArn = topicArn }); // Add the policy to the queue so SNS can send messages to the queue. var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn); sqsClient.SetQueueAttributes(new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string> { { QueueAttributeName.Policy, policy } } }); } static void DownloadAnArchive(string archiveId, AmazonGlacierClient client) { // Initiate job. InitiateJobRequest initJobRequest = new InitiateJobRequest() { VaultName = vaultName, JobParameters = new JobParameters() { Type = "archive-retrieval", ArchiveId = archiveId, Description = "This job is to download the archive.", SNSTopic = topicArn, } }; InitiateJobResponse initJobResponse = client.InitiateJob(initJobRequest); string jobId = initJobResponse.JobId; // Check queue for a message and if job completed successfully, download archive. ProcessQueue(jobId, client); } private static void ProcessQueue(string jobId, AmazonGlacierClient client) { var receiveMessageRequest = new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = 1 }; bool jobDone = false; while (!jobDone) { Console.WriteLine("Poll SQS queue"); ReceiveMessageResponse receiveMessageResponse = sqsClient.ReceiveMessage(receiveMessageRequest); if (receiveMessageResponse.Messages.Count == 0) { Thread.Sleep(10000 * 60); continue; } Console.WriteLine("Got message"); Message message = receiveMessageResponse.Messages[0]; Dictionary<string, string> outerLayer = JsonConvert.DeserializeObject<Dictionary<string, string>>(message.Body); Dictionary<string, object> fields = JsonConvert.DeserializeObject<Dictionary<string, object>>(outerLayer["Message"]); string statusCode = fields["StatusCode"] as string; if (string.Equals(statusCode, GlacierUtils.JOB_STATUS_SUCCEEDED, StringComparison.InvariantCultureIgnoreCase)) { long archiveSize = Convert.ToInt64(fields["ArchiveSizeInBytes"]); Console.WriteLine("Downloading job output"); DownloadOutput(jobId, archiveSize, client); // This where we save job output to the specified file location. } else if (string.Equals(statusCode, GlacierUtils.JOB_STATUS_FAILED, StringComparison.InvariantCultureIgnoreCase)) Console.WriteLine("Job failed... cannot download the archive."); jobDone = true; sqsClient.DeleteMessage(new DeleteMessageRequest() { QueueUrl = queueUrl, ReceiptHandle = message.ReceiptHandle }); } } private static void DownloadOutput(string jobId, long archiveSize, AmazonGlacierClient client) { long partSize = 4 * (long)Math.Pow(2, 20); // 4 MB. using (Stream fileToSave = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { long currentPosition = 0; do { GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest() { JobId = jobId, VaultName = vaultName }; long endPosition = currentPosition + partSize - 1; if (endPosition > archiveSize) endPosition = archiveSize; getJobOutputRequest.SetRange(currentPosition, endPosition); GetJobOutputResponse getJobOutputResponse = client.GetJobOutput(getJobOutputRequest); using (Stream webStream = getJobOutputResponse.Body) { CopyStream(webStream, fileToSave); } currentPosition += partSize; } while (currentPosition < archiveSize); } } public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[65536]; int length; while ((length = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, length); } } } }