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.
The .NET Framework uses the UTF-16 encoding (represented by the
UnicodeEncoding
class) to represent characters and strings. So you can useSystem.Text.Encoding.Unicode.GetBytes
to get bytes of string.For more information:
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.