本文整理汇总了C#中Amazon.S3.AmazonS3Client.ListBuckets方法的典型用法代码示例。如果您正苦于以下问题:C# AmazonS3Client.ListBuckets方法的具体用法?C# AmazonS3Client.ListBuckets怎么用?C# AmazonS3Client.ListBuckets使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Amazon.S3.AmazonS3Client
的用法示例。
在下文中一共展示了AmazonS3Client.ListBuckets方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main()
{
// Connect to Amazon S3 service with authentication
BasicAWSCredentials basicCredentials =
new BasicAWSCredentials("AKIAIIYG27E27PLQ6EWQ",
"hr9+5JrS95zA5U9C6OmNji+ZOTR+w3vIXbWr3/td");
AmazonS3Client s3Client = new AmazonS3Client(basicCredentials);
// Display all S3 buckets
ListBucketsResponse buckets = s3Client.ListBuckets();
foreach (var bucket in buckets.Buckets)
{
Console.WriteLine(bucket.BucketName);
}
// Display and download the files in the first S3 bucket
string bucketName = buckets.Buckets[0].BucketName;
Console.WriteLine("Objects in bucket '{0}':", bucketName);
ListObjectsResponse objects =
s3Client.ListObjects(new ListObjectsRequest() { BucketName = bucketName });
foreach (var s3Object in objects.S3Objects)
{
Console.WriteLine("\t{0} ({1})", s3Object.Key, s3Object.Size);
if (s3Object.Size > 0)
{
// We have a file (not a directory) --> download it
GetObjectResponse objData = s3Client.GetObject(
new GetObjectRequest() { BucketName = bucketName, Key = s3Object.Key });
string s3FileName = new FileInfo(s3Object.Key).Name;
SaveStreamToFile(objData.ResponseStream, s3FileName);
}
}
// Create a new directory and upload a file in it
string path = "uploads/new_folder_" + DateTime.Now.Ticks;
string newFileName = "example.txt";
string fullFileName = path + "/" + newFileName;
string fileContents = "This is an example file created through the Amazon S3 API.";
s3Client.PutObject(new PutObjectRequest() {
BucketName = bucketName,
Key = fullFileName,
ContentBody = fileContents}
);
Console.WriteLine("Created a file in Amazon S3: {0}", fullFileName);
// Share the uploaded file and get a download URL
string uploadedFileUrl = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
{
BucketName = bucketName,
Key = fullFileName,
Expires = DateTime.Now.AddYears(5)
});
Console.WriteLine("File download URL: {0}", uploadedFileUrl);
System.Diagnostics.Process.Start(uploadedFileUrl);
}
示例2: TestClientDispose
public void TestClientDispose()
{
IAmazonS3 client;
using(client = new AmazonS3Client())
{
var response = client.ListBuckets();
Assert.IsNotNull(response);
Assert.IsNotNull(response.ResponseMetadata);
Assert.IsNotNull(response.ResponseMetadata.RequestId);
Assert.IsFalse(string.IsNullOrEmpty(response.ResponseMetadata.RequestId));
}
AssertExtensions.ExpectException(() => client.ListBuckets(), typeof(ObjectDisposedException));
}
示例3: List
private static void List(AmazonS3Client client)
{
// Issue call
ListBucketsResponse listResponse = client.ListBuckets();
// View response data
Console.WriteLine("Buckets owner - {0}", listResponse.Owner.DisplayName);
foreach (S3Bucket bucket in listResponse.Buckets)
{
Console.WriteLine("Bucket {0}, Created on {1}", bucket.BucketName, bucket.CreationDate);
}
}
示例4: UseAwsSdk
/// <summary>
/// Uses the AWS SDK for .NET to talk to Tier 3 Object Storage
/// </summary>
private static void UseAwsSdk()
{
Console.WriteLine(":: Calling Tier 3 Object Storage from AWS SDK for .NET ::");
Console.WriteLine();
//create configuration that points to different URL
AmazonS3Config config = new AmazonS3Config()
{
ServiceURL = "ca.tier3.io"
};
AmazonS3Client client = new AmazonS3Client(adminAccessKey, adminAccessSecret, config);
/*
* List buckets
*/
Console.WriteLine("ACTION: List all the buckets");
ListBucketsResponse resp = client.ListBuckets();
foreach (S3Bucket bucket in resp.Buckets)
{
Console.WriteLine("-" + bucket.BucketName);
}
Console.WriteLine();
/*
* List objects in a single bucket
*/
Console.WriteLine("ACTION: Enter the name of a bucket to open: ");
string inputbucket = Console.ReadLine();
ListObjectsRequest objReq = new ListObjectsRequest() { BucketName = inputbucket };
ListObjectsResponse objResp = client.ListObjects(objReq);
foreach (S3Object obj in objResp.S3Objects)
{
Console.WriteLine("-" + obj.Key);
}
/*
* Upload object to bucket
*/
//Console.Write("Type [Enter] to upload an object to the opened bucket");
//Console.ReadLine();
//PutObjectRequest putReq = new PutObjectRequest() { BucketName = inputbucket, FilePath = @"C:\image.png", ContentType = "image/png" };
//PutObjectResponse putResp = client.PutObject(putReq);
//Console.WriteLine("Object uploaded.");
Console.ReadLine();
}
示例5: ActivateOptions
public override void ActivateOptions()
{
var client = new AmazonS3Client();
ListBucketsResponse response = client.ListBuckets();
bool found = response.Buckets.Any(bucket => bucket.BucketName == BucketName);
if (found == false)
{
client.PutBucket(new PutBucketRequest().WithBucketName(BucketName));
}
base.ActivateOptions();
}
示例6: DeleteAllBuckets
public static void DeleteAllBuckets()
{
using (var client = new AmazonS3Client(Settings.AccessKey, Settings.Secret))
{
var response = client.ListBuckets();
foreach (var bucket in response.Buckets)
{
DeleteAllBucketItems(bucket.BucketName);
client.DeleteBucket(bucket.BucketName);
}
}
}
示例7: TestCredentials
private static void TestCredentials(ProxyRefreshingAWSCredentials creds, bool expectFailure)
{
using (var client = new AmazonS3Client(creds))
{
try
{
client.ListBuckets();
Assert.IsFalse(expectFailure);
}
catch (AmazonClientException ace)
{
Assert.IsTrue(expectFailure);
Assert.IsNotNull(ace);
Assert.IsNotNull(ace.Message);
Assert.IsTrue(ace.Message.IndexOf("already") >= 0);
}
}
}
示例8: executeSomeBucketOperations
private void executeSomeBucketOperations(AmazonS3Config s3Config)
{
using (var s3Client = new AmazonS3Client(s3Config))
{
// Call ListBuckets first to verify that AmazonS3PostMarshallHandler.ProcessRequestHandlers
// correctly computes the endpoint when no bucket name is present.
var listBucketsResponse = s3Client.ListBuckets();
Assert.IsNotNull(listBucketsResponse);
Assert.IsFalse(string.IsNullOrEmpty(listBucketsResponse.ResponseMetadata.RequestId));
// Bonus call on ListObjects if we can find a bucket compatible with the test region (to avoid 301
// errors due to addressing bucket on wrong endpoint). This verifies that
// AmazonS3PostMarshallHandler.ProcessRequestHandlers correctly computes the endpoint when
// a bucket name is present.
string bucketName = null;
foreach (var bucket in listBucketsResponse.Buckets)
{
try
{
var bucketLocationResponse = s3Client.GetBucketLocation(bucket.BucketName);
if (string.IsNullOrEmpty(bucketLocationResponse.Location) && s3Config.RegionEndpoint == RegionEndpoint.USEast1)
bucketName = bucket.BucketName;
else if (string.Equals(s3Config.RegionEndpoint.SystemName, bucketLocationResponse.Location, StringComparison.OrdinalIgnoreCase))
bucketName = bucket.BucketName;
if (!string.IsNullOrEmpty(bucketName))
break;
}
catch(AmazonS3Exception e)
{
if (e.StatusCode != System.Net.HttpStatusCode.NotFound)
throw;
}
}
if (!string.IsNullOrEmpty(bucketName))
{
var listObjectsResponse = s3Client.ListObjects(new ListObjectsRequest { BucketName = bucketName });
Assert.IsNotNull(listObjectsResponse);
Assert.IsNotNull(listObjectsResponse.ResponseMetadata);
}
}
}
示例9: Main
public static void Main()
{
Debug.WriteLine("============================================");
Debug.WriteLine("Welcome to the AWS .NET SDK! Ready, Set, Go!");
Debug.WriteLine("============================================");
//The Amazon S3 client allows you to manage buckets and objects programmatically.
IAmazonS3 s3Client = new AmazonS3Client();
try
{
ListBucketsResponse response = s3Client.ListBuckets();
int numBuckets = 0;
if (response.Buckets != null && response.Buckets.Count > 0)
{
numBuckets = response.Buckets.Count;
}
Debug.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s)");
}
catch (Amazon.S3.AmazonS3Exception S3Exception)
{
//AmazonServiceException represents an error response from an AWS service.
//AWS service received the request but either found it invalid or encountered an error trying to execute it.
if (S3Exception.ErrorCode != null && (S3Exception.ErrorCode.Equals("InvalidAccessKeyId") || S3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Debug.WriteLine("Please check the provided AWS Credentials.");
Debug.Write("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
Debug.WriteLine(S3Exception.Message, S3Exception.InnerException);
}
else
{
Debug.WriteLine("Error Message: " + S3Exception.Message);
Debug.WriteLine("HTTP Status Code: " + S3Exception.StatusCode);
Debug.WriteLine("AWS Error Code: " + S3Exception.ErrorCode);
Debug.WriteLine("Request ID: " + S3Exception.RequestId);
}
}
finally
{
s3Client.Dispose();
};
}
示例10: TestSessionCredentials
public void TestSessionCredentials()
{
using (var sts = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient())
{
AWSCredentials credentials = sts.GetSessionToken().Credentials;
var originalS3Signature = AWSConfigsS3.UseSignatureVersion4;
AWSConfigsS3.UseSignatureVersion4 = true;
try
{
using (var ec2 = new Amazon.EC2.AmazonEC2Client(credentials))
{
var regions = ec2.DescribeRegions().Regions;
Console.WriteLine(regions.Count);
}
using (var s3 = new Amazon.S3.AmazonS3Client(credentials))
{
var buckets = s3.ListBuckets().Buckets;
Console.WriteLine(buckets.Count);
}
using (var swf = new Amazon.SimpleWorkflow.AmazonSimpleWorkflowClient(credentials))
{
var domains = swf.ListDomains(new Amazon.SimpleWorkflow.Model.ListDomainsRequest { RegistrationStatus = "REGISTERED" }).DomainInfos;
Console.WriteLine(domains.Infos.Count);
}
using (var swf = new Amazon.SimpleWorkflow.AmazonSimpleWorkflowClient(credentials, new Amazon.SimpleWorkflow.AmazonSimpleWorkflowConfig { SignatureVersion = "4" }))
{
var domains = swf.ListDomains(new Amazon.SimpleWorkflow.Model.ListDomainsRequest { RegistrationStatus = "REGISTERED" }).DomainInfos;
Console.WriteLine(domains.Infos.Count);
}
}
finally
{
AWSConfigsS3.UseSignatureVersion4 = originalS3Signature;
}
}
}
示例11: TestExplicitDualstackEndpoint
public void TestExplicitDualstackEndpoint()
{
var config = new AmazonS3Config
{
ServiceURL = "https://s3.dualstack.us-west-2.amazonaws.com"
};
using (var s3Client = new AmazonS3Client(config))
{
var listBucketsResponse = s3Client.ListBuckets();
Assert.IsNotNull(listBucketsResponse);
Assert.IsFalse(string.IsNullOrEmpty(listBucketsResponse.ResponseMetadata.RequestId));
}
}
示例12: TestHttpAccessOnDualstackEndpoint
public void TestHttpAccessOnDualstackEndpoint()
{
var config = new AmazonS3Config
{
UseDualstackEndpoint = true,
RegionEndpoint = RegionEndpoint.USWest2,
UseHttp = true
};
using (var s3Client = new AmazonS3Client(config))
{
var listBucketsResponse = s3Client.ListBuckets();
Assert.IsNotNull(listBucketsResponse);
Assert.IsFalse(string.IsNullOrEmpty(listBucketsResponse.ResponseMetadata.RequestId));
}
}
示例13: Random
/*
Sample call for upload:-
byte[] array = new byte[1024*1024*1024];
Random random = new Random();
random.NextBytes(array);
double timeTaken_Upload = Experiment.doRawCloudPerf(array, SynchronizerType.Azure, SynchronizeDirection.Upload, "fooContainer", "fooBlob");
double timeTaken_Download = Experiment.doRawCloudPerf(array, SynchronizerType.Azure, SynchronizeDirection.Download, "fooContainer", "fooBlob");
*
*
*/
public static double doRawCloudPerf(byte[] input, SynchronizerType synchronizerType,
SynchronizeDirection syncDirection, string exp_directory, Logger logger, string containerName=null, string blobName=null)
{
string accountName = ConfigurationManager.AppSettings.Get("AccountName");
string accountKey = ConfigurationManager.AppSettings.Get("AccountSharedKey");
DateTime begin=DateTime.Now, end=DateTime.Now;
if (synchronizerType == SynchronizerType.Azure)
{
#region azure download/upload
if (containerName==null)
containerName = "testingraw";
if(blobName==null)
blobName = Guid.NewGuid().ToString();
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, accountKey), true);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
if (syncDirection == SynchronizeDirection.Upload)
{
logger.Log("Start Stream Append");
container.CreateIfNotExist();
begin = DateTime.UtcNow;//////////////////////////////////////
try
{
using (MemoryStream memoryStream = new System.IO.MemoryStream(input))
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
blockBlob.UploadFromStream(memoryStream);
}
}
catch (Exception e)
{
}
end = DateTime.UtcNow;//////////////////////////////////////
logger.Log("End Stream Append");
}
if (syncDirection == SynchronizeDirection.Download)
{
logger.Log("Start Stream Get");
logger.Log("Start Stream GetAll");
try
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
byte[] blobContents = blockBlob.DownloadByteArray();
//if (File.Exists(blobName))
// File.Delete(blobName);
begin = DateTime.UtcNow;//////////////////////////////////////
// using (FileStream fs = new FileStream(blobName, FileMode.OpenOrCreate))
// {
byte[] contents = blockBlob.DownloadByteArray();
// fs.Write(contents, 0, contents.Length);
// }
}
catch (Exception e)
{
}
end = DateTime.UtcNow;//////////////////////////////////////
logger.Log("End Stream Get");
logger.Log("End Stream GetAll");
}
#endregion
}
else if (synchronizerType == SynchronizerType.AmazonS3)
{
#region amazon s3 stuff
if (containerName == null)
containerName = "testingraw";
if (blobName == null)
blobName = Guid.NewGuid().ToString();
AmazonS3Client amazonS3Client = new AmazonS3Client(accountName, accountKey);
if (syncDirection == SynchronizeDirection.Upload)
{
ListBucketsResponse response = amazonS3Client.ListBuckets();
foreach (S3Bucket bucket in response.Buckets)
{
if (bucket.BucketName == containerName)
{
break;
}
}
//.........这里部分代码省略.........
示例14: BucketSamples
public void BucketSamples()
{
{
#region ListBuckets Sample
// Create a client
AmazonS3Client client = new AmazonS3Client();
// Issue call
ListBucketsResponse response = client.ListBuckets();
// View response data
Console.WriteLine("Buckets owner - {0}", response.Owner.DisplayName);
foreach (S3Bucket bucket in response.Buckets)
{
Console.WriteLine("Bucket {0}, Created on {1}", bucket.BucketName, bucket.CreationDate);
}
#endregion
}
{
#region BucketPolicy Sample
// Create a client
AmazonS3Client client = new AmazonS3Client();
// Put sample bucket policy (overwrite an existing policy)
string newPolicy = @"{
""Statement"":[{
""Sid"":""BasicPerms"",
""Effect"":""Allow"",
""Principal"": ""*"",
""Action"":[""s3:PutObject"",""s3:GetObject""],
""Resource"":[""arn:aws:s3:::samplebucketname/*""]
}]}";
PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest
{
BucketName = "SampleBucket",
Policy = newPolicy
};
client.PutBucketPolicy(putRequest);
// Retrieve current policy
GetBucketPolicyRequest getRequest = new GetBucketPolicyRequest
{
BucketName = "SampleBucket"
};
string policy = client.GetBucketPolicy(getRequest).Policy;
Console.WriteLine(policy);
Debug.Assert(policy.Contains("BasicPerms"));
// Delete current policy
DeleteBucketPolicyRequest deleteRequest = new DeleteBucketPolicyRequest
{
BucketName = "SampleBucket"
};
client.DeleteBucketPolicy(deleteRequest);
// Retrieve current policy and verify that it is null
policy = client.GetBucketPolicy(getRequest).Policy;
Debug.Assert(policy == null);
#endregion
}
{
#region GetBucketLocation Sample
// Create a client
AmazonS3Client client = new AmazonS3Client();
// Construct request
GetBucketLocationRequest request = new GetBucketLocationRequest
{
BucketName = "SampleBucket"
};
// Issue call
GetBucketLocationResponse response = client.GetBucketLocation(request);
// View response data
Console.WriteLine("Bucket location - {0}", response.Location);
#endregion
}
{
#region PutBucket Sample
// Create a client
AmazonS3Client client = new AmazonS3Client();
// Construct request
PutBucketRequest request = new PutBucketRequest
{
//.........这里部分代码省略.........
示例15: Push
public string Push(AmazonS3Client s3Client, AmazonCodeDeployClient codeDeployClient)
{
var zipFileName = string.Format("{0}.{1}.{2}.zip", ApplicationSetName, Version, BundleName);
var tempPath = Path.Combine(Path.GetTempPath(), zipFileName + "." + Guid.NewGuid() + ".zip");
ZipFile.CreateFromDirectory(_bundleDirectory.FullName, tempPath, CompressionLevel.Optimal, false, Encoding.ASCII);
var allTheBuckets = s3Client.ListBuckets(new ListBucketsRequest()).Buckets;
if (!allTheBuckets.Exists(b => b.BucketName == Bucket))
{
s3Client.PutBucket(new PutBucketRequest { BucketName = Bucket, UseClientRegion = true });
}
var putResponse = s3Client.PutObject(new PutObjectRequest
{
BucketName = Bucket,
Key = zipFileName,
FilePath = tempPath,
});
var registration = new RegisterApplicationRevisionRequest
{
ApplicationName = CodeDeployApplicationName,
Description = "Revision " + Version,
Revision = new RevisionLocation
{
RevisionType = RevisionLocationType.S3,
S3Location = new S3Location
{
Bucket = Bucket,
BundleType = BundleType.Zip,
Key = zipFileName,
Version = Version
}
}
};
try
{
codeDeployClient.RegisterApplicationRevision(registration);
}
catch (ApplicationDoesNotExistException)
{
codeDeployClient.CreateApplication(new CreateApplicationRequest { ApplicationName = CodeDeployApplicationName });
codeDeployClient.RegisterApplicationRevision(registration);
}
return putResponse.ETag;
}