使用非默认权限将文件上载到Amazon S3

时间:2013-11-01 20:28:52

标签: c# amazon-web-services amazon-s3

我正在尝试使用.NET SDK将文件上传到Amazon S3。上传工作正常,只是将default permission应用于上传的文件,即“私有”。

我希望将上传文件的权限设置为'BucketOwnerFullControl'。

下面是我的代码,我不太清楚我需要做些什么才能让它正常工作。

    static string accessKeyID = "";
    static string secretAccessKey = "";
    static string existingBucketName = "bucket";

    static void Main(string[] args)
    {
        NameValueCollection appConfig = ConfigurationManager.AppSettings;
        accessKeyID = appConfig["accesskey"];
        secretAccessKey = appConfig["secretkey"];

        string[] files = Directory.GetFiles("C:\\amazontestdirectory");

            foreach (string fileName in files)
            {
                try
                {
                    TransferUtility fileTransferUtility = new TransferUtility(accessKeyID, secretAccessKey);

                    // Upload a file, file name is used as the object key name.
                    fileTransferUtility.Upload(fileName, existingBucketName);
                }
                catch (AmazonS3Exception s3Exception)
                {
                    Console.WriteLine("AWS error: " + s3Exception.Message, s3Exception.InnerException);

                    //Open a file for writing
                    string errorOutputFileName = System.IO.Path.GetFullPath("C:\\amazontestdirectory\\logs\\errorLog.txt");

                    //Get a StreamWriter class that can be used to write to the file
                    if (File.Exists(errorOutputFileName))
                    {
                        StreamWriter objStreamWriter;
                        objStreamWriter = File.AppendText(errorOutputFileName);
                        objStreamWriter.WriteLine();
                        objStreamWriter.WriteLine(DateTime.Now.ToString() + " - AWS error: " + s3Exception.Message, s3Exception.InnerException);

                        //Close the stream
                        objStreamWriter.Close();
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:4)

要在使用TransferUtility时设置权限,您需要使用TransferUtilityUploadRequest中的上传覆盖。这使您可以在上传文件时设置更高级的选项。

TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
{
    BucketName = existingBucketName,
    FilePath = fileName,
    CannedACL = S3CannedACL.BucketOwnerFullControl
};

// Upload a file, file name is used as the object key name.
fileTransferUtility.Upload(request);