public string DownloadFileContents(string remoteFilename, string versionID = "") { string tempFile = System.IO.Path.GetTempFileName(); TransferUtilityDownloadRequest req = new TransferUtilityDownloadRequest(); req.BucketName = CurrentBucketName; req.FilePath = tempFile; if (string.IsNullOrEmpty(versionID) == false) { req.VersionId = versionID; } req.Key = remoteFilename; req.WriteObjectProgressEvent += (s, e) => { if (FileProgressChanged != null) { FileProgressChanged(e.Key, e.TransferredBytes, e.TotalBytes, e.PercentDone); } }; _transfer.Download(req); string fileContents = File.ReadAllText(tempFile); File.Delete(tempFile); return(fileContents); }
public void DownloadImageFromS3(ImageModel imageToDownload, bool getThumbnail = false) { var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); var fileName = $"{imageToDownload.Key ?? imageToDownload.Id}.{imageToDownload.Extension}"; if (!getThumbnail) { var imageDownloadDirPath = $"files/images/{imageToDownload.Folder}/{fileName}"; var imagesBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToDownload.Folder}"; fileTransferUtility.Download(imageDownloadDirPath, imagesBucketName, fileName); _imagesCollection.UpdateOne <ImageModel>(image => image.Id == imageToDownload.Id, Builders <ImageModel> .Update.Set("Path", imageDownloadDirPath)); } else { var thumbnailDownloadDirPath = $"files/images/{imageToDownload.Folder}/thumbnails/{fileName}"; var thumbnailsBucketName = $"helpet/{_environment.EnvironmentName}/images/{imageToDownload.Folder}/thumbnails"; fileTransferUtility.Download(thumbnailDownloadDirPath, thumbnailsBucketName, fileName); _imagesCollection.UpdateOne <ImageModel>(image => image.Id == imageToDownload.Id, Builders <ImageModel> .Update.Set("ThumbnailPath", thumbnailDownloadDirPath)); } fileTransferUtility.Dispose(); client.Dispose(); }
[ExcludeFromCodeCoverage] //test method below public void DownloadButton_Click(object sender, EventArgs e) { TransferUtilityDownloadRequest request = new TransferUtilityDownloadRequest(); request.BucketName = "eecs393minesweeper"; String key = OnlineMapsList.SelectedItem.ToString() + ".map"; request.Key = key; request.FilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper\\" + key; utility.Download(request); ReadLocalFiles(); PopulateLocalList(); }
public async Task <IActionResult> DownloadRandom() { var files = await _libraryRepository.GetAllFilesAsync(); var random = new Random(); int index = random.Next(files.Count); var path = files[index].Path; try { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(_awsAccessKeyS3, _awsSecretKeyS3, RegionEndpoint.USEast1)); fileTransferUtility.Download(path, _bucketName, files[index].Name); var memory = new MemoryStream(); using (var stream = new FileStream(path, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; return(File(memory, GetContentType(path), Path.GetFileName(path))); } catch { return(NotFound()); } }
void Download(string fileName, long size, TransferProgressValidator <WriteObjectProgressArgs> progressValidator) { var key = fileName; var originalFilePath = Path.Combine(basePath, fileName); UtilityMethods.GenerateFile(originalFilePath, size); Client.PutObject(new PutObjectRequest { BucketName = bucketName, Key = key, FilePath = originalFilePath }); var downloadedFilePath = originalFilePath + ".dn"; var transferUtility = new TransferUtility(Client); var request = new TransferUtilityDownloadRequest { BucketName = bucketName, FilePath = downloadedFilePath, Key = key }; if (progressValidator != null) { request.WriteObjectProgressEvent += progressValidator.OnProgressEvent; } transferUtility.Download(request); UtilityMethods.CompareFiles(originalFilePath, downloadedFilePath); }
public async Task <IActionResult> Download(string fileName) { if (fileName == null) { return(Content("fileName not present")); } var path = Path.Combine(_storage, fileName); try { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(_awsAccessKeyS3, _awsSecretKeyS3, RegionEndpoint.USEast1)); fileTransferUtility.Download(path, _bucketName, fileName); } catch (Exception ex) { Console.WriteLine(ex); } try { var memory = new MemoryStream(); using (var stream = new FileStream(path, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; return(File(memory, GetContentType(path), Path.GetFileName(path))); } catch { return(NotFound()); } }
public void DownloadFromS3(S3File file, AmazonS3Client client) { if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null) { throw new Exception("S3 File is NULL or has some NULL attributes"); } try { TransferUtility fileTransferUtility = new TransferUtility(client); TransferUtilityDownloadRequest fileTransferUtilityRequest = new TransferUtilityDownloadRequest { BucketName = file.Bucket, FilePath = file.LocalFilePath, Key = file.RemoteFilePath, }; fileTransferUtility.Download(fileTransferUtilityRequest); } catch (Exception ex) { throw ex; } }
public void DownloadS3File(string localPath) { var request = new TransferUtilityDownloadRequest { BucketName = this.BucketName, Key = this.Key, FilePath = localPath }; var splitted = localPath.Split(new[] { BACK_SLASH }, StringSplitOptions.RemoveEmptyEntries); var directoryPath = string.Join(BACK_SLASH, splitted.Take(splitted.Length - 1)); DirectoryHelper.CreateDirectoryIfNotExists(directoryPath); try { using (var response = new TransferUtility(this.S3Client)) { Debug.WriteLine("Downloading " + request.Key); request.WriteObjectProgressEvent += TransferProgress; response.Download(request); } } catch (AmazonS3Exception aex) { const string FORMAT = "Couldn't save file ({0}:/{1})."; var message = string.Format(FORMAT, this.BucketName, this.Key); throw new FileNotFoundException(message, aex); } }
/// <summary> /// Download a specific file from a S3 bucket /// </summary> /// <param name="path"></param> public void DownloadFile(string path) { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1)); BasicAWSCredentials basicCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey), Amazon.RegionEndpoint.USEast1); ListObjectsRequest request = new ListObjectsRequest(); request.BucketName = bucketName; ListObjectsResponse response = s3Client.ListObjects(request.BucketName = bucketName, request.Prefix = path); try { S3Object obj = response.S3Objects[0]; string filename = filepath + "\\" + obj.Key; FileStream fs = File.Create(filename); fs.Close(); fileTransferUtility.Download(filename, bucketName, obj.Key); log.Info("File: " + obj.Key + " downloaded"); } catch (Exception ex) { log.Info(ex.Message + ex.StackTrace); } }
public void DownloadFile(string bucketName, string objectKey, string localFilePath) { IAmazonS3 client = new AmazonS3Client(this.RegionEndpoint); TransferUtility transferUtility = new TransferUtility(client); transferUtility.Download(localFilePath, bucketName, objectKey); }
public void DownloadFromS3(S3File file) { if (file is null || file.RemoteFilePath is null || file.Bucket is null || file.LocalFilePath is null) { throw new Exception("S3 File is NULL or has some NULL attributes"); } if (Credentials is null || Credentials.AWS_AccessKey is null || Credentials.AWS_SecretKey is null || Credentials.Region is null) { throw new CredentialsNotProvidedException(); } try { TransferUtility fileTransferUtility = new TransferUtility(getS3Client(Credentials)); TransferUtilityDownloadRequest fileTransferUtilityRequest = new TransferUtilityDownloadRequest { BucketName = file.Bucket, FilePath = file.LocalFilePath, Key = file.RemoteFilePath, }; fileTransferUtility.Download(fileTransferUtilityRequest); } catch (Exception ex) { throw ex; } }
// Download object to local file // Returns true on success, false on error. public override bool DownloadFile(String folder, String file, String outputFilePath) { try { this.Exception = null; int pos = outputFilePath.LastIndexOf("\\"); if (pos != -1) { outputFilePath = outputFilePath.Substring(0, pos); } TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(this.AccessKey, this.SecretKey, this.RegionEndpoint)); fileTransferUtility.Download(outputFilePath, folder, file); return(true); } catch (Exception ex) { this.Exception = ex; if (!this.HandleErrors) { throw ex; } return(false); } }
// Download object to local file // Returns true on success, false on error. public override bool DownloadFile(CloudFile file, String outputFilePath) { try { this.Exception = null; int pos = outputFilePath.LastIndexOf("\\"); if (pos != -1) { outputFilePath = outputFilePath.Substring(0, pos); } S3Object obj = file.StorageObject as S3Object; TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(this.AccessKey, this.SecretKey, this.RegionEndpoint)); fileTransferUtility.Download(outputFilePath, obj.BucketName, file.Name); return(true); } catch (Exception ex) { this.Exception = ex; if (!this.HandleErrors) { throw ex; } return(false); } }
/// <summary> /// Downloads the latest backup set from the Aws service. /// </summary> /// <param name="compressor">The compresor to use when decompressing the downloaded file.</param> /// <returns>The path to the downloaded and decompressed backup file.</returns> public string DownloadBackup(ICompressor compressor) { S3Object latest = this.GetLatestBackupItem(); string path = latest.Key; if (!String.IsNullOrEmpty(this.Target.AwsPrefix) && path.StartsWith(this.Target.AwsPrefix, StringComparison.OrdinalIgnoreCase)) { path = path.Substring(this.Target.AwsPrefix.Length); if (path.StartsWith("/", StringComparison.Ordinal)) { path = path.Substring(1); } } path = Path.Combine(TempDir, path); string fileName = Path.GetFileName(path); if (File.Exists(path)) { File.Delete(path); } TransferInfo info = new TransferInfo() { BytesTransferred = 0, FileName = fileName, FileSize = 0 }; using (TransferUtility transfer = new TransferUtility(S3Client)) { TransferUtilityDownloadRequest request = new TransferUtilityDownloadRequest() .WithBucketName(AwsConfig.BucketName) .WithFilePath(path) .WithKey(latest.Key); request.WriteObjectProgressEvent += (sender, e) => { info.BytesTransferred = e.TransferredBytes; info.FileSize = e.TotalBytes; this.Fire(this.TransferProgress, new TransferInfo(info)); }; this.Fire(this.TransferStart, new TransferInfo(info)); transfer.Download(request); } this.Fire(this.TransferComplete, new TransferInfo(info)); this.Fire(this.DecompressStart); string decompressedPath = compressor.Decompress(path); this.Fire(this.DecompressComplete); File.Delete(path); return(decompressedPath); }
public void TestDownloadFile(string filePath, string keyName) { TransferUtility fileTransferUtility = new TransferUtility( new AmazonS3Client("AKIAJO3YO2ATRVV5UQYA", "4+SelI41UmF0oO8IiXazTizmLy60C82Eaem2nonH", Amazon.RegionEndpoint.EUWest3)); fileTransferUtility.Download(filePath, bucketName, keyName); }
public ICustomActivityResult Execute() { var message = string.Empty; TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(AccessKey, SecretKey, Amazon.RegionEndpoint.USEast1)); fileTransferUtility.Download(File_Path + "\\" + Key, Bucket, Key); message = "Success"; return(this.GenerateActivityResult(message)); }
public static void DownloadSetting(RegionEndpoint _bucketRegion, string _destinationsPath, string _bucketName) { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(_bucketRegion)); Directory.CreateDirectory(Path.GetDirectoryName(_destinationsPath)); fileTransferUtility.Download(_destinationsPath, _bucketName, "time.txt"); }
private void DownloadFile(string fileNameInS3) { IAmazonS3 client = new AmazonS3Client(); TransferUtility utility = new TransferUtility(client); TransferUtilityDownloadRequest request = new TransferUtilityDownloadRequest(); request.Key = fileNameInS3; request.BucketName = "teasy"; request.FilePath = Path.Combine(Path.GetTempPath(), "T-Easy/" + fileNameInS3); utility.Download(request); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public String FunctionHandler(FileEvent input, ILambdaContext context) { // GetObjectRequest request = new GetObjectRequest{ // BucketName = bucketName, // Key = keyName // } foreach (String key in input.fileKeys) { Console.WriteLine(key); } string bucketName = input.bucketName; List <bool> list = new List <bool>(); client = new AmazonS3Client(bucketRegion); foreach (String keyName in input.fileKeys) { string filePath = "/tmp/" + keyName; TransferUtility fileTransferUtility = new TransferUtility(client); try { fileTransferUtility.Download(filePath, bucketName, keyName); } catch (AmazonS3Exception ex) { S3Error errorMessage = new S3Error() { Error = ex.ToString() }; return(JsonConvert.SerializeObject(errorMessage)); } // string[] files = Directory.GetFiles("/tmp/"); // foreach(string item in files){ // Console.WriteLine(item); // } VirusScan.ICAP icap = new VirusScan.ICAP("<AVSCAN-IP>", 1344, "SYMCScanResp-AV", 100); try{ Console.WriteLine("File Scanning"); bool res = icap.scanFile(filePath); list.Add(res); File.Delete(filePath); Console.WriteLine(res + "\n"); } catch (Exception ex) { Console.WriteLine("Could not scan file " + filePath + ex); return("Could not scan file " + filePath + ex); } } Response response = new Response() { list = list }; string output = JsonConvert.SerializeObject(response); return(output); }
private async Task DownloadMovie(string fileS3Name, string fileName) { try { var pathAndFileName = downloadLocation + "\\" + fileName; TransferUtility utility = new TransferUtility(s3Client); utility.Download(pathAndFileName, bucketName, fileS3Name); } catch (Exception ex) { throw; } }
public void DoUpload() { string accessKey = "*** access Key ***"; string secretKey = "*** secret Key ***"; string bucketName = "*** bucket name ***"; string uploadFileName = "*** upload FileName ***"; //e.g. test.xml string downloadFileName = "*** download FileName ***"; //e.g. test.png AmazonS3Config s3Config = new AmazonS3Config { ServiceURL = "s3.amazonaws.com", RegionEndpoint = Amazon.RegionEndpoint.APSoutheast1 }; //ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => //{ // Console.WriteLine("Got callback"); // return true; //}; BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3Client client = new AmazonS3Client(basicAWSCredentials, s3Config); for (int i = 0; i < 2; i++) { try { string appDir = AppDomain.CurrentDomain.BaseDirectory; TransferUtility fileTransUtil = new TransferUtility(client); if (i == 0) { fileTransUtil.Upload(Path.Combine(appDir, uploadFileName), bucketName, uploadFileName); } else { fileTransUtil.Download(Path.Combine(appDir, downloadFileName), bucketName, downloadFileName); } } catch (AmazonS3Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("Amazon error code:{0}", e.ErrorCode ?? "None")); System.Diagnostics.Debug.Write(e.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.ToString()); } } }
private void VerifyObjectWithTransferUtility(string bucketName) { var transferUtility = new TransferUtility(Client); var filePath = Path.GetFullPath("downloadedFile.txt"); transferUtility.Download(new TransferUtilityDownloadRequest { BucketName = bucketName, Key = key, FilePath = filePath }); var fileContents = File.ReadAllText(filePath); VerifyContents(fileContents); }
public void DownloadFileAsync(string fileName, string targetPath) { var fileTransferUtility = new TransferUtility(client); var fileTransferUtilityRequest = new TransferUtilityDownloadRequest { BucketName = bucketName, FilePath = Path.Combine(targetPath, Path.GetFileName(fileName)), Key = $"{fileName}" }; fileTransferUtility.Download(fileTransferUtilityRequest); logger.Info($"Object {fileName} downloaded."); }
public static void DownloadFile(RegionEndpoint _bucketRegion, string _destinationsPath, string _extractDirectory, string _sourcePath, string _bucketName) { try { TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(_bucketRegion)); Directory.CreateDirectory(Path.GetDirectoryName(_destinationsPath)); fileTransferUtility.Download(_destinationsPath, _bucketName, "source.zip"); extractFile(_sourcePath, _extractDirectory); } catch (AmazonS3Exception s3Exception) { Console.WriteLine(s3Exception.Message, s3Exception.InnerException); } }
private void btnDownload_Click(object sender, EventArgs e) { if (listView1.FocusedItem != null) { String filePath = "/"; if (listView1.FocusedItem != null) { filePath += listView1.FocusedItem.Text; } utility.Download(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), listView1.FocusedItem.Text), "chinozuku", treeView1.SelectedNode.FullPath + filePath); MessageBox.Show("Download Complete"); } else { MessageBox.Show("Please choose a file to download", "No File Choosen", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void DownloadImage(string altId, ImageType imageType) { try { var clientId = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.AccessKey); var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.SecretKey); var bucketName = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.BucketName); QrCodeGenerator.GenerateQrCode(altId); var s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")); var transferUtility = new TransferUtility(s3Client); transferUtility.Download(Path.Combine(QrCodeGenerator.ApplicationPath(), ImageFilePathProvider.GetImageFilePath(altId, imageType)), bucketName, ImageFilePathProvider.GetImageFilePath(altId, imageType)); } catch (Exception ex) { _logger.Log(LogCategory.Error, ex); } }
public void DownloadFileFromS3(FileModel fileToDownload) { var client = new AmazonS3Client(_generalSettings.S3AccessKey, _generalSettings.S3SecretKey, RegionEndpoint.USEast1); var fileTransferUtility = new TransferUtility(client); var fileName = $"{fileToDownload.Key ?? fileToDownload.Id}.{fileToDownload.Extension}"; var fileDownloadDirPath = $"files/docs/{fileToDownload.Folder}/{fileToDownload.Extension}/{fileName}"; var filesBucketName = $"helpet/{_environment.EnvironmentName}/docs/{fileToDownload.Folder}/{fileToDownload.Extension}"; fileTransferUtility.Download(fileDownloadDirPath, filesBucketName, fileName); _filesCollection.UpdateOne <FileModel>(document => document.Id == fileToDownload.Id, Builders <FileModel> .Update.Set("Path", fileDownloadDirPath)); fileTransferUtility.Dispose(); client.Dispose(); }
private void DownloadMissingOrOutdatedVideos() { foreach (Product product in ShelfInventory.Instance.ProductList()) { string filePath = GetFilePathForProduct(product); string key = product.productID + videoFileExtension; if (!File.Exists(filePath) || IsOutdated(filePath, key)) { try { Util.LogSuccess("Downloading " + key + "... ", false); fileTransferUtility.Download(filePath, productVideoBucket, key); Util.LogSuccess("Download complete"); } catch (Exception) { Util.LogError("Unable to retrieve object with key: " + key); } } } }
public string DownloadFile(string fileName, string targetPath) { var targetFileName = Path.Combine(targetPath, fileName.Replace(":", "")); var fileTransferUtility = new TransferUtility(client); var fileTransferUtilityRequest = new TransferUtilityDownloadRequest { BucketName = bucketName, FilePath = targetFileName, Key = $"{fileName}" }; fileTransferUtility.Download(fileTransferUtilityRequest); logger.Info($"Object {fileName} downloaded."); return(targetFileName); }
public void BlockTransferUtilityDownloadTest() { var transferUtility = new TransferUtility(RegionEndpoint.USWest2); try { transferUtility.Download(new TransferUtilityDownloadRequest { BucketName = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/mybanner", Key = "test.txt", FilePath = @"c:\foo\bar\test.txt" }); } catch (AmazonS3Exception e) { var expectedMessage = "Download does not support S3 Object Lambda resources"; Assert.AreEqual(expectedMessage, e.Message); } }