How to get a consistent byte representation of a string in C# without explicitly specifying encoding?
Hello! I'm a beginner C# developer, and I have a problem with converting strings to bytes. I need to send string data over the network and save it to a file, but I noticed that when reading back, the data sometimes differs.\n\nI tried using `Encoding.Default`, but the result is different on different computers. Then I tried `Encoding.ASCII`, but it doesn't support Russian letters and other Unicode characters. Now I'm doing this:\n\n```csharp\nstring text = "Привет, мир!";\nbyte[] bytes = Encoding.UTF8.GetBytes(text);\nstring restored = Encoding.UTF8.GetString(bytes);\n```\n\nThis works, but the question is: why do I always have to explicitly specify `Encoding.UTF8`? Can't .NET determine the correct encoding by itself? After all, strings in C# are already stored as Unicode internally. Why isn't there a simple method to
No answers yet.
Log in to leave an answer