问题描述
假设我的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控件中的序列化数据指定哪种编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!