Which encoding should I specify for the serialized data from TextBox controls

╄→尐↘猪︶ㄣ 提交于 2019-12-20 04:23:15

问题


Suppose that I have a TextBox in my WinForms application.

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

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

string json = JsonConvert.SerializeObject(credentials);

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

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

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

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?

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


回答1:


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.

For more information:

  • Character Encoding in the .NET Framework



回答2:


Any Unicode encoding (UTF-7, UTF-8, UTF-16, UTF-32, …) can be used to encode Unicode characters. UTF-8 is possibly the most compact, depending on the writing systems used on your text.



来源:https://stackoverflow.com/questions/35792490/which-encoding-should-i-specify-for-the-serialized-data-from-textbox-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!