我将 Amazon S3 sdk 与 .Net 一起用于 Xamarin 项目,我需要先检查一个对象是否存在于存储桶中,然后再对其进行处理。我不能使用该Exists
属性,Amazon.S3.IO.S3FileInfo
因为由于某种原因我不能Amazon.S3.IO
在我的代码中使用命名空间。(使用它会让我的生活变得更轻松),所以我使用以下代码(我从 S3FileInfo here的源代码中获得)
public bool PackageExistsOnS3(string bucket, string key)
{
bool bucketExists;
return ExistsWithBucketCheck(out bucketExists, bucket, key);
}
private bool ExistsWithBucketCheck(out bool bucketExists, string bucket, string key)
{
bucketExists = true;
try
{
var request = new GetObjectMetadataRequest
{
BucketName = bucket,
Key = AWSS3Helper.EncodeKey(key)
};
((Amazon.Runtime.Internal.IAmazonWebServiceRequest) request).AddBeforeRequestHandler(AWSS3Helper
.FileIORequestEventHandler);
AmazonS3Client _client = new AmazonS3Client(_accessKey, _secretKey, _regionEndPoint);
// If the object doesn't exist then a "NotFound" will be thrown
// I DO NOT WANT TO USE THE METADATAASYNC VERSION HERE, I JUST WANT THE REGULAR VERSION BUT I CANNOT DO THAT
_client.GetObjectMetadataAsync();
//var test = _client.GetObjectMetadata;
return true;
}
catch (AmazonS3Exception e)
{
if (string.Equals(e.ErrorCode, "NoSuchBucket"))
{
bucketExists = false;
return false;
}
else if (string.Equals(e.ErrorCode, "NotFound"))
{
return false;
}
throw;
}
}
AWSS3Helper 的代码如下:
internal static class AWSS3Helper
{
internal static string EncodeKey(string key)
{
return key.Replace('\\', '/');
}
internal static string DecodeKey(string key)
{
return key.Replace('/', '\\');
}
internal static void FileIORequestEventHandler(object sender, RequestEventArgs args)
{
WebServiceRequestEventArgs wsArgs = args as WebServiceRequestEventArgs;
if (wsArgs != null)
{
string currentUserAgent = wsArgs.Headers[AWSSDKUtils.UserAgentHeader];
wsArgs.Headers[AWSSDKUtils.UserAgentHeader] = currentUserAgent + " FileIO";
}
}
}
任何人都知道如何避免使用这个异步函数?它会阻止我返回一个布尔值,如果我必须返回一些我需要的东西,我需要在使用这个函数的地方使用 Await,这意味着我需要使每个使用它的函数成为异步函数,我真的很想避免复杂化随之而来的。