我应该为TextBox控件中的序列化数据指定哪种编码 [英] Which encoding should I specify for the serialized data from TextBox controls

查看:159
本文介绍了我应该为TextBox控件中的序列化数据指定哪种编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的WinForms应用程序中有一个TextBox.

Suppose that I have a TextBox in my WinForms application.

当用户单击按钮时,应用程序应通过TCP发送存储在此TextBox中的序列化值.

When user clicks a button, the application should send a serialized value stored in this TextBox via TCP.

对于序列化,我使用的是Newtonsoft.Json库,如下所示:

For the serialization I'm using Newtonsoft.Json library like this:

string json = JsonConvert.SerializeObject(credentials);

credentials是保存TextBox值的类的对象.

Where credentials is the object of class that holds TextBox's value.

然后我需要通过TcpClient类通过网络发送它:

Then I need to send it over network via TcpClient class:

TcpClient client = new TcpClient(IpAddress, Port);
NetworkStream stream = client.GetStream();
// ???

,但是我需要先将json字符串转换为字节数组,所以我必须指定文本编码.我应该指定哪种文本编码非常安全?

but I need to convert the json string to the byte array first, so I have to specify a text encoding. Which text encoding should I specify to be pretty safe?

我不能仅将其设置为ASCII,因为用户可以输入Unicode字符.

I can't just set it to ASCII because user can enter unicode characters.

推荐答案

.NET Framework使用UTF-16编码(由 UnicodeEncoding 类)代表字符和字符串.因此,您可以使用System.Text.Encoding.Unicode.GetBytes获取字符串字节.

The .NET Framework uses the UTF-16 encoding (represented by the UnicodeEncoding class) to represent characters and strings. So you can use System.Text.Encoding.Unicode.GetBytes to get bytes of string.

有关更多信息:

这篇关于我应该为TextBox控件中的序列化数据指定哪种编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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