在C#.NET中对非ASCII字符进行编码 [英] Encode non ascii characters in C# .NET

查看:152
本文介绍了在C#.NET中对非ASCII字符进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序发送的电子邮件中添加自定义标头.标头名称只能包含ASCII字符,但是对于该值,用户可能会输入UTF-8字符,因此我必须对其进行base64编码.另外,我还必须将它们解码回UTF-8,以便在用户界面中将其展示给用户.

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?

推荐答案

要使用UTF8作为基础编码,将.net字符串转换为base 64:

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

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

并撤消该过程:

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

完全有可能跳过UTF8步骤.但是,相比于UTF16,UTF8通常会产生较小的有效负载,因此,我建议使用UTF8作为基础编码.

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.

当您说用户可以输入UTF8字符时,我不确定您的意思. .net框架使用UTF16作为其工作字符串编码.您在.net中使用的字符串始终使用UTF16编码.也许您只是在说文本可以包含非ASCII字符.

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.

这篇关于在C#.NET中对非ASCII字符进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆