Upload or Store a file in Amazon S3 bucket c#

  • 1216 View's
  • 0 Comment's

To store your data in Amazon S3, you work with resources known as buckets and objects. A bucket is a container for objects. An object is a file and any metadata that describes that file.
The instructions in this article are designed for a C# ASP .NET MVC application. They should work elsewhere with tweaks for your situation. This assumes that your AWS creds are already set up. It is based on a Microsoft article about file uploads.

first, add  AWSS3 SDK from the console or NuGet package.

        string FileName = "SalaryReport" + ".pdf";
		string FilePath =  "https://csharpcode.in/folder/"+ FileName;

		bool isFileSave = UploadFileAmazonS3(ConfigurationManager.AppSettings["AMAZON_API_KEY"], 
		ConfigurationManager.AppSettings["AMAZON_API_SECRET"], FileName, FilePath, ref s3FileName);

        /// <summary>
        /// Upload file on AWS server.
        /// </summary>
        /// <returns>Return status and s3 bucket url</returns>
        public bool UploadFileAmazonS3(string awsAccessKeyId, string bucketName, string awsSecretAccessKey, string fileName, string filePath, ref string s3filePath)
            string s3DirectoryName = string.Empty;
            string s3FileName = fileName;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            s3filePath = "s3://" + bucketName + "/" + s3FileName;
            return SendFileToS3(awsAccessKeyId, awsSecretAccessKey, fileStream, bucketName, s3DirectoryName, s3FileName);
        /// <summary>
        /// Send file on AWS server.
        /// </summary>
        /// <returns>Return status and s3 bucket url</returns>
        public bool SendFileToS3(string awsAccessKeyId, string awsSecretAccessKey, System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
            IAmazonS3 client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.EUWest2);
            TransferUtility utility = new TransferUtility(client);
            TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
            if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
                request.BucketName = bucketName; //no subdirectory just bucket name  
            {   // subdirectory and bucket name  
                request.BucketName = bucketName + @"/" + subDirectoryInBucket;
            request.Key = fileNameInS3; //file name up in S3  
            request.InputStream = localFilePath;
            utility.Upload(request); //commensing the transfer  
            return true; //indicate that the file was sent  

0 Comment's

Comment Form