本文整理汇总了C#中Amazon.S3.AmazonS3Client类的典型用法代码示例。如果您正苦于以下问题:C# AmazonS3Client类的具体用法?C# AmazonS3Client怎么用?C# AmazonS3Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AmazonS3Client类属于Amazon.S3命名空间,在下文中一共展示了AmazonS3Client类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: UploadDataFileAsync
public async Task UploadDataFileAsync(string data, string storageKeyId, string storageSecret, string region)
{
var regionIdentifier = RegionEndpoint.GetBySystemName(region);
using (var client = new AmazonS3Client(storageKeyId, storageSecret, regionIdentifier))
{
try
{
var putRequest1 = new PutObjectRequest
{
BucketName = AwsBucketName,
Key = AwsBucketFileName,
ContentBody = data,
ContentType = "application/json"
};
await client.PutObjectAsync(putRequest1);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new SecurityException("Invalid Amazon S3 credentials - data was not uploaded.", amazonS3Exception);
}
throw new HttpRequestException("Unspecified error attempting to upload data: " + amazonS3Exception.Message, amazonS3Exception);
}
var response = await client.GetObjectAsync(AwsBucketName, AwsBucketFileName);
using (var reader = new StreamReader(response.ResponseStream))
{
Debug.WriteLine(await reader.ReadToEndAsync());
}
}
}
开发者ID:Benrnz,项目名称:BudgetAnalyser,代码行数:35,代码来源:S3MobileDataUploader.cs
示例2: SendImageToS3
public static Boolean SendImageToS3(String key, Stream imageStream)
{
var success = false;
using (var client = new AmazonS3Client(RegionEndpoint.USWest2))
{
try
{
PutObjectRequest request = new PutObjectRequest()
{
InputStream = imageStream,
BucketName = BucketName,
Key = key
};
client.PutObject(request);
success = true;
}
catch (Exception ex)
{
// swallow everything for now.
}
}
return success;
}
开发者ID:raynjamin,项目名称:Sitecore-S3-Media,代码行数:27,代码来源:S3Client.cs
示例3: ImportIntoS3Tasks
public ImportIntoS3Tasks()
{
appHost = new BasicAppHost().Init();
var s3Client = new AmazonS3Client(AwsConfig.AwsAccessKey, AwsConfig.AwsSecretKey, RegionEndpoint.USEast1);
s3 = new S3VirtualPathProvider(s3Client, AwsConfig.S3BucketName, appHost);
}
开发者ID:ServiceStackApps,项目名称:RazorRockstars,代码行数:7,代码来源:ImportIntoS3Tasks.cs
示例4: Configure
public override void Configure(Container container)
{
JsConfig.EmitCamelCaseNames = true;
Plugins.Add(new RazorFormat());
//Comment out 2 lines below to change to use local FileSystem instead of S3
var s3Client = new AmazonS3Client(AwsConfig.AwsAccessKey, AwsConfig.AwsSecretKey, RegionEndpoint.USEast1);
VirtualFiles = new S3VirtualPathProvider(s3Client, AwsConfig.S3BucketName, this);
container.Register<IPocoDynamo>(c => new PocoDynamo(AwsConfig.CreateAmazonDynamoDb()));
var db = container.Resolve<IPocoDynamo>();
db.RegisterTable<Todos.Todo>();
db.RegisterTable<EmailContacts.Email>();
db.RegisterTable<EmailContacts.Contact>();
db.InitSchema();
//AWS Auth
container.Register<ICacheClient>(new DynamoDbCacheClient(db, initSchema:true));
container.Register<IAuthRepository>(new DynamoDbAuthRepository(db, initSchema:true));
Plugins.Add(CreateAuthFeature());
//EmailContacts
ConfigureSqsMqServer(container);
ConfigureEmailer(container);
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(EmailContacts.CreateContact).Assembly);
}
开发者ID:ServiceStackApps,项目名称:AwsApps,代码行数:27,代码来源:AppHost.cs
示例5: S3TraceListener
public S3TraceListener(string initializeData)
{
string[] commands = initializeData.Split(',');
foreach (var command in commands)
{
string[] subcommand = command.Split('=');
switch (subcommand[0])
{
case "logfile":
LogFileName = string.Format("{0}.{1}.log", GetUnixTime(), subcommand[1]);
break;
case "bucket":
_bucketName = subcommand[1];
break;
}
}
if (LogFileName == null || _bucketName == null)
{
throw new Exception("Not valid parameters. Pass logfile=,bucketname=.");
}
if (_amazonConfig == null)
{
_amazonConfig = new EnvironmentAWSCredentials();
_s3Client = new AmazonS3Client(_amazonConfig);
_stringFile = new List<string>();
}
}
开发者ID:rodvdka,项目名称:S3TraceListener,代码行数:30,代码来源:S3TraceListener.cs
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (upload.PostedFile != null && upload.PostedFile.ContentLength > 0 && !string.IsNullOrEmpty(Request["awsid"]) && !string.IsNullOrEmpty(Request["awssecret"]) && !string.IsNullOrEmpty(this.bucket.Text))
{
var name = "s3readersample/" + ImageUploadHelper.Current.GenerateSafeImageName(upload.PostedFile.InputStream, upload.PostedFile.FileName);
var client = new Amazon.S3.AmazonS3Client(Request["awsid"], Request["awssecret"], Amazon.RegionEndpoint.EUWest1);
//For some reason we have to buffer the file in memory to prevent issues... Need to research further
var ms = new MemoryStream();
upload.PostedFile.InputStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
var request = new Amazon.S3.Model.PutObjectRequest() { BucketName = this.bucket.Text, Key = name, InputStream = ms, CannedACL = Amazon.S3.S3CannedACL.PublicRead };
var response = client.PutObject(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
result.Text = "Successfully uploaded " + name + "to bucket " + this.bucket.Text;
}
else
{
result.Text = response.HttpStatusCode.ToString();
}
}
}
开发者ID:eakova,项目名称:resizer,代码行数:27,代码来源:Upload.aspx.cs
示例7: S3Reader2
public S3Reader2(NameValueCollection args )
{
s3config = new AmazonS3Config();
buckets = args["buckets"];
vpath = args["prefix"];
asVpp = NameValueCollectionExtensions.Get(args, "vpp", true);
Region = args["region"] ?? "us-east-1";
s3config.UseHttp = !NameValueCollectionExtensions.Get(args, "useSsl", false);
if (!string.IsNullOrEmpty(args["accessKeyId"]) && !string.IsNullOrEmpty(args["secretAccessKey"])) {
S3Client = new AmazonS3Client(args["accessKeyId"], args["secretAccessKey"], s3config);
} else {
S3Client = new AmazonS3Client(null, s3config);
}
includeModifiedDate = NameValueCollectionExtensions.Get(args, "includeModifiedDate", includeModifiedDate);
includeModifiedDate = NameValueCollectionExtensions.Get(args, "checkForModifiedFiles", includeModifiedDate);
RequireImageExtension = NameValueCollectionExtensions.Get(args, "requireImageExtension", RequireImageExtension);
UntrustedData = NameValueCollectionExtensions.Get(args, "untrustedData", UntrustedData);
CacheUnmodifiedFiles = NameValueCollectionExtensions.Get(args, "cacheUnmodifiedFiles", CacheUnmodifiedFiles);
}
开发者ID:stukalin,项目名称:ImageResizer,代码行数:28,代码来源:S3Reader.cs
示例8: DeleteFile
public void DeleteFile(String filename)
{
String key = filename;
var amazonClient = new AmazonS3Client(_keyPublic, _keySecret);
var deleteObjectRequest = new DeleteObjectRequest { BucketName = _bucket, Key = key };
var response = amazonClient.DeleteObject(deleteObjectRequest);
}
开发者ID:Rychard,项目名称:SqlServerBackup,代码行数:7,代码来源:AmazonS3Helper.cs
示例9: GetComputeNode
public IComputeNode GetComputeNode()
{
IComputeNode compute_node = null;
try
{
//amazon client
using (var client = new AmazonS3Client())
{
//download request
using (var response = client.GetObject(new GetObjectRequest()
.WithBucketName(AmazonBucket)
.WithKey(BermudaConfig)))
{
using (StreamReader reader = new StreamReader(response.ResponseStream))
{
//read the file
string data = reader.ReadToEnd();
//deserialize
compute_node = new ComputeNode().DeserializeComputeNode(data);
if(compute_node.Catalogs.Values.Cast<ICatalog>().FirstOrDefault().CatalogMetadata.Tables.FirstOrDefault().Value.DataType == null)
compute_node.Catalogs.Values.Cast<ICatalog>().FirstOrDefault().CatalogMetadata.Tables.FirstOrDefault().Value.DataType = typeof(UDPTestDataItems);
compute_node.Init(CurrentInstanceIndex, AllNodeEndpoints.Count());
}
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
}
return compute_node;
}
开发者ID:yonglehou,项目名称:Bermuda,代码行数:33,代码来源:LocalHostEnvironmentConfiguration.cs
示例10: CreateAndCheckTestBucket
private void CreateAndCheckTestBucket()
{
TestBucketIsReady = false;
USEast1Client = new AmazonS3Client(RegionEndpoint.USEast1);
USWest1Client = new AmazonS3Client(RegionEndpoint.USWest1);
var sessionCredentials = new AmazonSecurityTokenServiceClient().GetSessionToken().Credentials;
USEast1ClientWithSessionCredentials = new AmazonS3Client(sessionCredentials, RegionEndpoint.USEast1);
TestBucket = USWest1Client.ListBuckets().Buckets.Find(bucket => bucket.BucketName.StartsWith(BucketPrefix));
if (TestBucket == null)
{
// add ticks to bucket name because the bucket namespace is shared globally
var bucketName = BucketPrefix + DateTime.Now.Ticks;
// Create the bucket but don't run the test.
// If the bucket is ready the next time this test runs we'll test then.
USWest1Client.PutBucket(new PutBucketRequest()
{
BucketRegion = S3Region.USW1,
BucketName = bucketName,
});
}
else if (TestBucket.CreationDate.AddHours(TemporaryRedirectMaxExpirationHours) < DateTime.Now)
{
BucketRegionDetector.BucketRegionCache.Clear();
TestBucketIsReady = true;
}
}
开发者ID:aws,项目名称:aws-sdk-net,代码行数:27,代码来源:BucketRegionTestRunner.cs
示例11: GetTargetAppVersion
public Guid? GetTargetAppVersion(Guid targetKey, Guid appKey)
{
try
{
using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
{
using (var res = client.GetObject(new GetObjectRequest()
{
BucketName = Context.BucketName,
Key = GetTargetAppVersionInfoPath(targetKey, appKey),
}))
{
using (var stream = res.ResponseStream)
{
return Utils.Serialisation.ParseKey(stream);
}
}
}
}
catch (AmazonS3Exception awsEx)
{
if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw new DeploymentException(string.Format("Failed getting version for app with key \"{0}\" and target with the key \"{1}\".", appKey, targetKey), awsEx);
}
}
}
开发者ID:danielrbradley,项目名称:Plywood,代码行数:31,代码来源:TargetAppVersions.cs
示例12: Start
// Use this for initialization
void Start () {
// ResultText is a label used for displaying status information
Debug.Log("hallo1");
Debug.Log("hallo2");
S3Client = new AmazonS3Client(Credentials);
Debug.Log("hallo3");
ResultText.text = "Fetching all the Buckets";
S3Client.ListBucketsAsync(new ListBucketsRequest(), (responseObject) =>
{
ResultText.text += "\n";
if (responseObject.Exception == null)
{
ResultText.text += "Got Response \nPrinting now \n";
responseObject.Response.Buckets.ForEach((s3b) =>
{
ResultText.text += string.Format("bucket = {0}, created date = {1} \n",
s3b.BucketName, s3b.CreationDate);
});
}
else
{
ResultText.text += "Got Exception \n";
}
});
}
开发者ID:jjenner689,项目名称:frog,代码行数:30,代码来源:S3Script.cs
示例13: TestSerializingExceptions
public void TestSerializingExceptions()
{
using(var client = new Amazon.S3.AmazonS3Client())
{
try
{
var fakeBucketName = "super.duper.fake.bucket.name.123." + Guid.NewGuid().ToString();
client.ListObjects(fakeBucketName);
}
catch(AmazonS3Exception e)
{
TestException(e);
}
var s3pue = CreateS3PostUploadException();
TestException(s3pue);
var doe = CreateDeleteObjectsException();
TestException(doe);
var aace = new AdfsAuthenticationControllerException("Message");
TestException(aace);
#pragma warning disable 618
var ccre = new CredentialCallbackRequiredException("Message");
TestException(ccre);
var afe = new AuthenticationFailedException("Message");
TestException(afe);
#pragma warning restore 618
}
}
开发者ID:aws,项目名称:aws-sdk-net,代码行数:35,代码来源:General.cs
示例14: DeleteObjectList
/// <summary>AWS S3 여러 객체 삭제</summary>
public DeleteObjectsResponse DeleteObjectList(List<string> pKeyList)
{
try
{
using (AmazonS3Client client = new AmazonS3Client())
{
DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest();
multiObjectDeleteRequest.BucketName = strAwsBucketName;
foreach (string key in pKeyList)
{
multiObjectDeleteRequest.AddKey(key);
}
DeleteObjectsResponse response = client.DeleteObjects(multiObjectDeleteRequest);
//response.DeleteErrors.Count = 실패한 삭제 객체
//response.DeletedObjects.Count = 성공한 삭제 객체
//.Key, .Code, .Message로 정보 확인 가능.
return response;
}
}
catch (AmazonS3Exception amazonS3Exception)
{
throw amazonS3Exception;
}
}
开发者ID:chae87,项目名称:First,代码行数:28,代码来源:AwsCmm.cs
示例15: EnvioS3
public EnvioS3(StringBuilder log, string arquivo, string accessKey, string secretKey, string bucketName)
{
_log = log;
_arquivo = arquivo;
_bucketName = bucketName;
_client = new AmazonS3Client(accessKey, secretKey);
}
开发者ID:hesenger,项目名称:Backup,代码行数:7,代码来源:EnvioS3.cs
示例16: TestPostUpload
public void TestPostUpload()
{
var region = RegionEndpoint.USWest1;
using (var client = new AmazonS3Client(region))
{
var bucketName = S3TestUtils.CreateBucket(client);
client.PutACL(new PutACLRequest
{
BucketName = bucketName,
CannedACL = S3CannedACL.BucketOwnerFullControl
});
var credentials = GetCredentials(client);
try
{
var response = testPost("foo/bar/content.txt", bucketName, testContentStream("Line one\nLine two\nLine three\n"), "", credentials, region);
Assert.IsNotNull(response.RequestId);
Assert.IsNotNull(response.HostId);
Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
}
finally
{
AmazonS3Util.DeleteS3BucketWithObjects(client, bucketName);
}
}
}
开发者ID:rajdotnet,项目名称:aws-sdk-net,代码行数:27,代码来源:RegionsTest.cs
示例17: TestLocation
public void TestLocation()
{
foreach (var location in new S3Region[] { S3Region.USW1, S3Region.EUC1 })
{
string bucketName = null;
var region = RegionEndpoint.GetBySystemName(location.Value);
using (var client = new AmazonS3Client(region))
{
try
{
bucketName = UtilityMethods.SDK_TEST_PREFIX + DateTime.Now.Ticks;
client.PutBucket(new PutBucketRequest
{
BucketName = bucketName,
BucketRegion = location
});
var returnedLocation = client.GetBucketLocation(new GetBucketLocationRequest
{
BucketName = bucketName
}).Location;
Assert.AreEqual(location, returnedLocation);
}
finally
{
if (bucketName != null)
AmazonS3Util.DeleteS3BucketWithObjects(client, bucketName);
}
}
}
}
开发者ID:rajdotnet,项目名称:aws-sdk-net,代码行数:34,代码来源:RegionsTest.cs
示例18: GetFile
public static GetObjectResponse GetFile(AwsCommonParams commonParams,
string bucketName, string filePath)
{
// We need to strip off any leading '/' in the path or
// else it creates a path with an empty leading segment
// This also implements behavior consistent with the
// edit counterpart routine for verification purposes
if (filePath.StartsWith("/"))
filePath = filePath.Substring(1);
using (var s3 = new Amazon.S3.AmazonS3Client(
commonParams.ResolveCredentials(),
commonParams.RegionEndpoint))
{
var s3Requ = new Amazon.S3.Model.GetObjectRequest
{
BucketName = bucketName,
//Prefix = filePath,
Key = filePath,
};
//var s3Resp = s3.ListObjects(s3Requ);
try
{
var s3Resp = s3.GetObject(s3Requ);
return s3Resp;
}
catch (AmazonS3Exception ex)
when (ex.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}
}
开发者ID:bseddon,项目名称:ACMESharp,代码行数:35,代码来源:AwsS3ChallengeHandler.cs
示例19: AmazonS3VirtualDirectory
/// <summary>
/// Initializes a new instance of the <see cref="AmazonS3VirtualDirectory"/> class.
/// </summary>
/// <param name="provider">The virtual path provider.</param>
/// <param name="virtualPath">The virtual path to the resource represented by this instance.</param>
public AmazonS3VirtualDirectory(AmazonS3VirtualPathProvider provider, string virtualPath)
: base(virtualPath)
{
_client = new AmazonS3Client(new AmazonS3Config {ServiceURL = "s3.amazonaws.com", CommunicationProtocol = Protocol.HTTP});
_provider = provider;
_virtualPath = virtualPath;
}
开发者ID:mattbrailsford,项目名称:BrickPile,代码行数:12,代码来源:AmazonS3VirtualDirectory.cs
示例20: UploadFile
public async Task UploadFile(string name,IStorageFile storageFile)
{
var s3Client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);
var transferUtilityConfig = new TransferUtilityConfig
{
ConcurrentServiceRequests = 5,
MinSizeBeforePartUpload = 20 * MB_SIZE,
};
try
{
using (var transferUtility = new TransferUtility(s3Client, transferUtilityConfig))
{
var uploadRequest = new TransferUtilityUploadRequest
{
BucketName = ExistingBucketName,
Key = name,
StorageFile = storageFile,
// Set size of each part for multipart upload to 10 MB
PartSize = 10 * MB_SIZE
};
uploadRequest.UploadProgressEvent += OnUploadProgressEvent;
await transferUtility.UploadAsync(uploadRequest);
}
}
catch (AmazonServiceException ex)
{
// oResponse.OK = false;
// oResponse.Message = "Network Error when connecting to AWS: " + ex.Message;
}
}
开发者ID:prashanthganathe,项目名称:PersonalProjects,代码行数:30,代码来源:AmazonFileBucketTransferUtil.cs
注:本文中的Amazon.S3.AmazonS3Client类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论