使用C#从Azure Blob复制到AWS S3

时间:2017-10-21 09:07:07

标签: c# azure amazon-s3 azure-functions azure-blob-storage

请注意,这是我第一次用C#做任何事情,所以请善待,我可能会犯一些非常基本的错误。 (是的,我知道我不应该硬编码密钥,但会在代码完成我想要的时候修复它。)

我正在尝试创建一个Azure函数,将Blob存储中的所有新项目复制到AWS S3。我已经设法使用本文中的代码从blob复制到blob:https://cmatskas.com/copy-azure-blob-data-between-storage-accounts-using-functions/

我尝试修改该代码,而不是保存到AWS S3存储桶。虽然此代码成功编译并为我提供了成功的日志,但它不会复制任何文件。有什么想法吗?

using System;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public async static void Run(CloudBlockBlob myBlob, TraceWriter log) 
{
    await CopyBlob(myBlob, log);
}

private async static Task CopyBlob(CloudBlockBlob myBlob, TraceWriter log)
{
    var existingBucketName = "bucketname";
    var keyName = "backup";
    var accessKey = "key";
    var secretKey = "secretkey";

    TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(accessKey,secretKey,Amazon.RegionEndpoint.eu-west-2));

    log.Info("Starting Copy");

    try{
        using (var stream = await myBlob.OpenReadAsync())
        {
            await fileTransferUtility.UploadAsync(stream, existingBucketName, keyName);
        }
        log.Info("Copy completed");

    }
    catch(Exception ex){
        log.Error(ex.Message);
        log.Info("Copy failed");
    }
    finally{
        log.Info("Operation completed");
    }
}

编辑:让它适用于将来发现这一点的任何人。

using System;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public async static void Run(CloudBlockBlob myBlob, TraceWriter log) 
{
    await CopyBlob(myBlob, log);
}

private async static Task CopyBlob(CloudBlockBlob myBlob, TraceWriter log)
{
    var existingBucketName = "bucketname";
    var keyName = myBlob.Name;
    var accessKey = "accesskey";
    var secretKey = "secretkey";

    TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(accessKey,secretKey,Amazon.RegionEndpoint.eu-west-2));

    log.Info("Starting Copy");

    try{
        using (var stream = await myBlob.OpenReadAsync())
        {
            await fileTransferUtility.UploadAsync(stream,existingBucketName,keyName);
        }
        log.Info("Copy completed");

    }
    catch(Exception ex){
        log.Error(ex.Message);
        log.Info("Copy failed");
    }
    finally{
        log.Info("Operation completed");
    }
}

1 个答案:

答案 0 :(得分:0)

您应该看到有关此问题的警告,但您的void方法可能会导致此问题。

请将您的功能代码更新为以下内容:

public async static Task Run(CloudBlockBlob myBlob, TraceWriter log) 
{
    await CopyBlob(myBlob, log);
}

请注意从voidTask

的更改