7

I want to add a custom header to the emails my application is sending out. The header name can only contain ASCII chars, but for the value and users could potentially enter UTF-8 characters and I have to base64-encode them. Also I have to decode them back to UTF-8 to show them back to the user in the UI.

What's the best way to do this?

4
  • stackoverflow.com/q/497813/629926 Commented Nov 23, 2011 at 19:34
  • Possible dup of stackoverflow.com/questions/1888066/encode-string-to-utf8 Commented Nov 23, 2011 at 19:35
  • 1
    Define "encode." Do you want it to be readable when encoded? You can strip all the non-ASCII characters but you won't be able to go back to UTF-8. Otherwise, you can use base-64 encoding but you won't be able to read it without decoding it (or you "learn" how to read in base-64). Commented Nov 23, 2011 at 19:45
  • Good point, i want base64. updated the question Commented Nov 23, 2011 at 19:46

2 Answers 2

10

To convert from a .net string to base 64, using UTF8 as the underlying encoding:

string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(text));

And to reverse the process:

string text = Encoding.UTF8.GetString(Convert.FromBase64String(base64));

It is perfectly possible to skip the UTF8 step. However, UTF8 typically results in a smaller payload that UTF16 and so I would recommend using UTF8 as the underlying encoding.


I'm not sure what you mean when you say that the user can enter UTF8 characters. The .net framework uses UTF16 as its working string encoding. The strings you use in .net are always encoded with UTF16. Perhaps you are just meaning that the text can contain non-ASCII characters.

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

2 Comments

I updated the question, I want base64 encoding. I don't care about human readability as long as I can decode it.
@crdx I don't know what you mean.
3

To encode the string:

var someUtf8Str = "ఠఠfoobarఠఠ";
var bytes = Encoding.UTF8.GetBytes(someUtf8Str);
var asBase64Str = Convert.ToBase64String(bytes);

To decode it:

var bytes = Convert.FromBase64String(asBase64Str);
var asUtf8Str = Encoding.UTF8.GetString(bytes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.