,

Upload file to Amazon S3 bucket – code example C#

Posted by

Adds an object to a bucket. You must have WRITE permissions on a bucket to add an object to it.

Note

  • To successfully complete the PutObject request, you must have the s3:PutObject in your IAM permissions.
  • To successfully change the objects acl of your PutObject request, you must have the s3:PutObjectAcl in your IAM permissions.
  • To successfully set the tag-set with your PutObject request, you must have the s3:PutObjectTagging in your IAM permissions.
  • The Content-MD5 header is required for any request to upload an object with a retention period configured using Amazon S3 Object Lock. For more information about Amazon S3 Object Lock, see Amazon S3 Object Lock Overview in the Amazon S3 User Guide.
 
// Connect to Amazon S3 service with authentication      
     BasicAWSCredentials basicCredentials =
                new BasicAWSCredentials("AmazonAccessKeyID",
                "AmazonAccessKey");
     AmazonS3Client client= new AmazonS3Client(basicCredentials, Amazon.RegionEndpoint.APSoutheast1);
     try  
     {  
       PutObjectRequest putRequest = new PutObjectRequest  
       {  
         BucketName = "<bucketName>",  
         Key =  "<FileName>",  
         ContentBody = "<fileContent>",  
         ContentType = "text/csv" // can be any file type  
       };  
       PutObjectResponse response = client.PutObject(putRequest);  
       if (response.HttpStatusCode.ToString() == "OK")  
       {  
         Console.WriteLine("File uploaded to S3");  
         return true;  
       }  
       else  
       {  
         Console.WriteLine("File not uploaded to S3");  
         return false;  
       }  
     }  
     catch (AmazonS3Exception amazonS3Exception)  
     {  
       if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))  
       {  
         Console.WriteLine($"Check the provided AWS Credentials, {amazonS3Exception.Message}");  
       }  
       else  
       {  
         Console.WriteLine($"Check the provided AWS Credentials, {amazonS3Exception.Message}");  
       }  
         
     }  
     catch (Exception ex)  
     {  
       Console.WriteLine(ex.Message);  
         
     }