检查S3对象是否存在的最佳方法是什么?
问题描述:
当前,我创建一个GetObjectMetaDataRequest
,如果GetObjectMetaDataResponse
抛出异常则表示该对象不存在.有没有一种更好的方法可以在不下载文件的情况下检查文件是否存在.
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.
答
您可以使用S3FileInfo类和此类的Exists方法,它会帮助您检查文件是否存在而不下载文件.请参阅下面的示例,我使用了AWSSDK 3.1.6 .net(3.5):
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;
}
}