public static async Task DownloadS3ObjectAsync(string downloadDir, string objectKey) { try { var settings = await GetSettingsAsync(); var downloadInfo = new DownloadObjectInfo { DownloadDirectory = downloadDir, ObjectKey = objectKey }; AmazonS3Client client = new AmazonS3Client( settings.AWSAccessKeyID, settings.AWSSecretAccessKey, RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName)); var request = new GetObjectRequest { BucketName = settings.AWSS3Bucket, Key = objectKey }; var response = await client.GetObjectAsync(request); await SaveObjectAsync(response, downloadInfo); } catch (Exception ex) { Debug.WriteLine(ex.Message); DownloadError?.Invoke("Error during download"); throw ex; } }
private static async Task SaveObjectAsync(GetObjectResponse response, DownloadObjectInfo info) { response.WriteObjectProgressEvent += Response_WriteObjectProgressEvent; string checkedFilePath = CheckFilePath(info); await response.WriteResponseStreamToFileAsync(checkedFilePath, false, new CancellationToken()); DownloadSuccess?.Invoke($"Backup downloaded {info.ObjectKey} to {Path.Combine(info.DownloadDirectory, checkedFilePath)}"); }
private static string CheckFilePath(DownloadObjectInfo info) { // start: does file already exist? // yes: rename // name contains '.'? // yes: split and rename with n // no: append n to name // n++ // goto start // no: download var file = info.ObjectKey; var splits = info.ObjectKey.Split('.'); string baseName = ""; for (int i = 0; i < splits.Count() - 1; i++) { baseName += splits[i] + '.'; } baseName = baseName.TrimEnd('.'); int n = 0; while (File.Exists(Path.Combine(info.DownloadDirectory, file))) { n++; if (splits.Count() > 1) { file = $"{baseName} ({n})." + splits[splits.Count() - 1]; } else { file = $"{info.ObjectKey} ({n})"; } } var checkedFilePath = Path.Combine(info.DownloadDirectory, file); return(checkedFilePath); }