问题
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?
回答1:
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.
回答2:
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);
来源:https://stackoverflow.com/questions/8247966/encode-non-ascii-characters-in-c-sharp-net