为什么AmazonS3Util.DoesS3BucketExist总是返回true?

时间:2018-02-07 20:04:48

标签: c# amazon-s3

我正在尝试检查是否存在S3存储桶。

浏览AWS API for .NET,我发现AmazonS3Util.DoesS3BucketExist 我认为这正是我所需要的。

虽然对于存储桶返回true,但我知道存在不幸的是,如果存储桶不存在,它也会返回true。

我通过IAM用户连接到AWS账户;我相信这可以用作其他功能,例如列出存储桶及其内容可以正常运行。

以下是一个示例控制台应用程序:

using System;
using Amazon.S3.Transfer;
using Amazon.S3.Util;

namespace S3FileSystemSample1
{
    class Program
    {        
        static void Main(string[] args)
        {
            //string bucketName = "realbucket"; // returns true which is expected
            string bucketName = "randombucket"; // also returns true which is not expected.

            TransferUtility _transferUtility = new TransferUtility();

            bool bucketExists = AmazonS3Util.DoesS3BucketExist(_transferUtility.S3Client, bucketName);

            if(bucketExists)
            {
                Console.WriteLine("Bucket Exists");
            }
            else
            {
                Console.WriteLine("Bucket DOES NOT Exists");
            }

        }

    }
}

我做错了什么?

更新:智能感知显示的内容 enter image description here

在这个例子中,我以不同的方式创建了AmazonS3Client,但没有成功 - 它继续返回true。

using System;
using Amazon.S3;
using Amazon.S3.Util;

namespace S3FileSystemSample1
{
    class Program
    {        
        static void Main(string[] args)
        {
            //string bucketName = "realbucket";
            string bucketName = "randombucket";

            IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2);

            bool bucketExists = AmazonS3Util.DoesS3BucketExist(client, bucketName);

            if (bucketExists)
            {
                Console.WriteLine("Bucket Exists");
            }
            else
            {
                Console.WriteLine("Bucket DOES NOT Exists");
            }            
        }                
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为存储桶名称为globally unique。在这种情况下,randombucket实际上是一个真正的桶。这对我来说是真实的: -

private static void DoesBucketExist(BasicAWSCredentials credentials, RegionEndpoint regionEndpoint)
{
    using (var client = new AmazonS3Client(credentials, regionEndpoint))
    {
        var doesS3BucketExist = AmazonS3Util.DoesS3BucketExist(client, "randombucket");
        Console.WriteLine(doesS3BucketExist);
    }
}

然而这不是: -

private static void DoesBucketExist(BasicAWSCredentials credentials, RegionEndpoint regionEndpoint)
{
    using (var client = new AmazonS3Client(credentials, regionEndpoint))
    {
        var doesS3BucketExist = AmazonS3Util.DoesS3BucketExist(client, Guid.NewGuid().ToString());
        Console.WriteLine(doesS3BucketExist);
    }
}

希望有所帮助!

修改*您可以访问http://randombucket.s3.amazonaws.com/进一步确认这一点,并且您会看到自己获得Access Denied,而如果您访问http://50820dfd-428d-47ff-879e-dbcac3acf139.s3.amazonaws.com/,则会获得NoSuchBucket