How to convert a UTF-8 byte array to a string in C#?
Hello everyone! I'm a beginner C# developer and I've run into a problem. I'm receiving a byte array from a network stream (TCP socket) that represents text in UTF-8 encoding. I need to convert this `byte[]` back to a regular `string` so I can output it to the console or process it.
The problem is that I don't understand how to do this correctly. Direct conversion via `(string)buffer` doesn't work, the compiler complains. I tried using `Encoding.Default.GetString(buffer)`, but I get gibberish instead of Russian text. Here's an example of the code I have:
```csharp
byte[] utf8Bytes = new byte[] { 208, 161, 208, 176, 208, 189, 208, 186, 209, 130 }; // This is "Санкт" in UTF-8
string result = Encoding.Default.GetString(utf8Bytes);
Console.WriteLine(result); // Outputs
No answers yet.
Log in to leave an answer