what's best way to check if a S3 object exists?

懵懂的女人 提交于 2020-01-14 07:32:27

问题


Currently, I make a GetObjectMetaDataRequest, if the GetObjectMetaDataResponse throw an exception means the object doesn't exist. Is there a better way to check whether the file exists without downloading the file.


回答1:


you can use S3FileInfo class and Exists method of this class it will hep you to check if file exists without download the file .see the example below I used the 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;
                }
    }



回答2:


Try this solution, it works for me.

AmazonS3Client client = new AmazonS3Client(accessKey, secretKey, regionEndpoint);       
S3FileInfo s3FileInfo = new S3FileInfo(client, bucketName, fileName);
s3FileInfo.Exists ? return true:return false;



回答3:


There is no ListObjectRequest, but instead a ListObjectsRequest where you cannot specify the Key. You then have to go through all the objects to find the one you want. I am currently looking in to it since I seem to get time out errors whilst downloading the file. (If anyone has some idea how to solve that feel free to comment).

You could instead try the List Parts Request if you happen to know the upload id.

Other than that I have no idea. Would like to have a chat with the person who wrote the S3 api...




回答4:


You're probably going to have to use the REST API yourself, as the method suggested, internally just does exactly the same thing (try...catch on the request)




回答5:


Yes.

You can use a ListObjectsRequest. Use the Marker property, and retrieve only 1 element.



来源:https://stackoverflow.com/questions/3321625/whats-best-way-to-check-if-a-s3-object-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!