什么是检查S3对象是否存在的最佳方法?

Qui*_*ncy 9 c# amazon-s3

目前,我做了一个GetObjectMetaDataRequest,如果GetObjectMetaDataResponse抛出一个异常意味着该对象不存在.有没有更好的方法来检查文件是否存在而不下载文件.

Lui*_*cho 9

你可以使用这个类的S3FileInfo类和Exists方法来检查文件是否存在而不下载文件.请参阅下面的示例我使用了AWSSDK 3.1.6 .net(3.5):

public static  bool ExistsFile()
{
    BasicAWSCredentials basicCredentials = new BasicAWSCredentials("my access key", "my secretkey");
                AmazonS3Config configurationClient = new AmazonS3Config();
                configurationClient.RegionEndpoint = RegionEndpoint.EUCentral1;

                try
                {
                    using (AmazonS3Client clientConnection = new AmazonS3Client(basicCredentials, configurationClient))
                    {

                        S3FileInfo file = new S3FileInfo(clientConnection, "mybucket", "FolderNameUniTest680/FileNameUnitTest680");
                        return file.Exists;//if the file exists return true, in other case false
                    }
                }
                catch(Exception ex)
                {
                    return false;
                }
    }
Run Code Online (Sandbox Code Playgroud)


Ada*_*son 8

如果您的情况与我类似,并且正在使用 .Net Core 并且无法访问 Amazon.S3.IO(和 S3FileInfo 方法),则可以使用异步 GetObjectMetadataRequest 方法执行以下操作:

static private AmazonS3Client s3Client = new AmazonS3Client();

public static async Task<bool> FileExistsS3Async(string _bucket, string _key)
{
      GetObjectMetadataRequest request = new GetObjectMetadataRequest()
      {
            BucketName = _bucket,
            Key = _key
      };

      try
      {
            await s3Client.GetObjectMetadataAsync(request);
            return true;
      }
      catch (AmazonS3Exception exception)
      {
            return false;
      }
}
Run Code Online (Sandbox Code Playgroud)

当我在 Unity 游戏中调用时,此功能对我有用。您还可以使用以下命令同步调用上述函数:

bool exists = Task.Run(()=>FileExistsS3Async(_bucket, _key)).Result;
Run Code Online (Sandbox Code Playgroud)


Sri*_*ri7 5

试试这个解决方案,它对我有用。

AmazonS3Client client = new AmazonS3Client(accessKey, secretKey, regionEndpoint);       
S3FileInfo s3FileInfo = new S3FileInfo(client, bucketName, fileName);
return s3FileInfo.Exists;
Run Code Online (Sandbox Code Playgroud)


cof*_*ine -1

是的。

您可以使用 ListObjectsRequest。使用 Marker 属性,并仅检索 1 个元素。