0

I have code that downloads HTML file from AWS S3 and convert it to base64

Here is code

 public async Task<string> DownloadFromS3(string bucketName, string fileName)
    {
        var getObjectRequest = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = fileName
        };

        var getObjectResponse = await _s3Client.GetObjectAsync(getObjectRequest);

        using (var fileMemoryStream = new MemoryStream())
        {
            await getObjectResponse.ResponseStream.CopyToAsync(fileMemoryStream);

            var imageBytes = fileMemoryStream.ToArray();

            return Convert.ToBase64String(imageBytes);
        }
    }

after this, in some part of code, I need to convert it back to HTML (not file, just plain HTML)

How I can do this?

11
  • 2
    Convert.FromBase64String ? Commented Apr 28, 2021 at 11:52
  • 1
    @EugeneSukh there are dozens of duplicate questions and thousands of Google hits. Crowcoder is right. Simply googling for c# convert base64 returns 900K hits with the first this duplicate SO question Commented Apr 28, 2021 at 12:01
  • 1
    What's the point of this code? If you already have the HTML text, use it. Don't convert it to BASE64. If you know the content is UTF8-encoded, Encoding.UTF8.GetString(imageBytes) is enough. Commented Apr 28, 2021 at 12:04
  • 2
    @EugeneSukh this isn't a matter of opinion. You retrieved some bytes using a stream. You can use those bytes directly or convert them to a string. There's no point in converting them to BASE64, then back to the original bytes, then to the string you needed in the first place. Encoding.UTF8.GetString(imageBytes) would get you the HTML text. Even that wastes RAM by buffering the bytes. You could use var reader=new StreamReader(getObjectResponse.ResponseStream); var html=reader.ReadToEnd(); and get that string directly Commented Apr 28, 2021 at 12:07
  • 2
    What you wrote uses 5 times the size of the HTML file at least. There's a copy in the MemoryStream, imageBytes, the Base64 string, the buffer returned by FromBase64String (which is identical to imageBytes) and finally the bytes string. If you used a StreamReader you'd only have a single copy Commented Apr 28, 2021 at 12:12

1 Answer 1

-1

First of all we need to convert from base64 string to byte[] and than get string from it

var attachmentString = await _awsService.DownloadFromS3(Environment.GetEnvironmentVariable("S3_BUCKET_EMAIL_TEMPLATES"),url);

var bytes = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(attachmentString));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.