public static async System.Threading.Tasks.Task<bool> DoesS3BucketExistAsync(IAmazonS3 s3Client, string bucketName)
{
if (s3Client == null)
{
throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
}
if (String.IsNullOrEmpty(bucketName))
{
throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
}
var request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Expires = DateTime.Now.AddDays(1),
Verb = HttpVerb.HEAD,
Protocol = Protocol.HTTP
};
var url = s3Client.GetPreSignedURL(request);
var uri = new Uri(url);
var httpRequest = WebRequest.Create(uri) as HttpWebRequest;
httpRequest.Method = "HEAD";
var concreteClient = s3Client as AmazonS3Client;
if (concreteClient != null)
{
concreteClient.ConfigureProxy(httpRequest);
}
try
{
#if PCL
var result = httpRequest.BeginGetResponse(null, null);
using (var httpResponse = httpRequest.EndGetResponse(result) as HttpWebResponse)
#else
using (var httpResponse = await httpRequest.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse)
#endif
{
// If all went well, the bucket was found!
return true;
}
}
catch (WebException we)
{
using (var errorResponse = we.Response as HttpWebResponse)
{
if (errorResponse != null)
{
var code = errorResponse.StatusCode;
return code != HttpStatusCode.NotFound &&
code != HttpStatusCode.BadRequest;
}
// The Error Response is null which is indicative of either
// a bad request or some other problem
return false;
}
}
}
#endif