Created
September 29, 2016 15:30
-
-
Save paladique/8c15b24da621d5d75759ae425d166015 to your computer and use it in GitHub Desktop.
Add a new object to an S3 Bucket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SomeClass | |
{ | |
// Change the AWSProfileName to the profile you want to use in the App.config file. | |
// See http://docs.aws.amazon.com/AWSSdkDocsNET/latest/DeveloperGuide/net-dg-config-creds.html for more details. | |
// You must also sign up for an Amazon S3 account for this to work | |
// See http://aws.amazon.com/s3/ for details on creating an Amazon S3 account | |
// Change the bucketName and keyName fields to values that match your bucketname and keyname | |
string bucketName = "bucketname"; | |
string keyName = "testpage"; | |
/* | |
Add this stuff in to your web/app config or else client variable will throw an exception | |
<appSettings> | |
<add key="AwsAccessKey" value=""/> | |
<add key="AwsSecretKey" value=""/> | |
</appSettings> | |
*/ | |
IAmazonS3 client = new AmazonS3Client(RegionEndpoint.USEast1); | |
void SomeClass() | |
{ | |
WritingAnObject(); | |
} | |
void WritingAnObject() | |
{ | |
try | |
{ | |
// simple object put | |
PutObjectRequest request = new PutObjectRequest() | |
{ | |
ContentBody = "this is a test", | |
BucketName = bucketName, | |
Key = keyName, | |
ContentType = "text/html", | |
}; | |
PutObjectResponse response = client.PutObject(request); | |
request.Metadata.Add("title", "the title"); | |
client.PutObject(request); | |
} | |
catch (AmazonS3Exception amazonS3Exception) | |
{ | |
if (amazonS3Exception.ErrorCode != null && | |
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || | |
amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) | |
{ | |
Console.WriteLine("Please check the provided AWS Credentials."); | |
Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); | |
} | |
else | |
{ | |
Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment