Download file from S3 bucket - code example C#

When you download an object, you get all of the object's metadata and a stream from which to read the contents. You should read the content of the stream as quickly as possible because the data is streamed directly from Amazon S3 and your network connection will remain open until you read all the data or close the input stream. You do the following to get an object:

  • Execute the getObject method by providing bucket name and object key in the request.

  • Execute one of the GetObjectResponse methods to process the stream.

The following are example :
 

  // Connect to Amazon S3 service with authentication  
       BasicAWSCredentials basicCredentials =  
         new BasicAWSCredentials("AmazonAccessKeyID",  
         "AmazonAccessKey");  
       AmazonS3Client s3Client = new AmazonS3Client(basicCredentials, Amazon.RegionEndpoint.APSoutheast1);  
       MemoryStream ms = null;  
       try  
       {  
         GetObjectRequest getObjectRequest = new GetObjectRequest  
         {  
           BucketName = "<bucketName>",  
           Key = "<FilePath>"  //eg: folder1/folder2/file.csv
         };  
         using (var response = s3Client.GetObject(getObjectRequest))  
         {  
           if (response.HttpStatusCode == HttpStatusCode.OK)  
           {  
             using (ms = new MemoryStream())  
             {  
               response.ResponseStream.CopyTo(ms);  
             }  
           }  
         }  
         if (ms is null || ms.ToArray().Length < 1)  
         {  
           throw new FileNotFoundException(string.Format("The document '{0}' is not found", "<FilePath>"));  
         }  
         byte[] bytesInStream = ms.ToArray(); // simpler way of converting to array  
         ms.Close();  
         Response.Clear();  
         Response.ContentType = "application/force-download";  
         Response.AddHeader("content-disposition", "attachment;  filename=name_you_file.csv");  
         Response.BinaryWrite(bytesInStream);  
         Response.End();  
       }  
       catch (Exception)  
       {  
         throw;  
       }  
     }  

 

 

 Back to listing