78.4k views
5 votes
How to convert string to utf-8 in c#

1 Answer

2 votes

Final answer:

To convert a string to UTF-8 in C#, you can use the System.Text.Encoding.UTF8.GetBytes method. This will encode the string into a UTF-8 byte array which can be used for external systems that require UTF-8 encoded data. To convert back from UTF-8, use the Get String method with the UTF-8 byte array to get a readable string.

Step-by-step explanation:

To convert a string to UTF-8 in C#, you must first understand that a string in .NET is composed of UTF-16 encoded characters. However, when you interact with systems that require UTF-8 encoding, you will need to convert the string into a byte array with the proper encoding. The System. Text. Encoding class provides the functionality to accomplish this. Here's an example of how to perform the conversion: string original String = "The string to convert"; byte[] utf8Bytes = Encoding.UTF8.GetBytes(original String);

This code snippet first declares a string variable and initializes it with the text that you want to convert. Then, it utilizes the Get Bytes method of the UTF8 property of the Encoding class to convert the string into a UTF-8 encoded byte array. In some cases, you might need to go the other way and convert a UTF-8 byte array back into a readable string. To do this, you would use the Get String method: byte[] utf8Bytes = // existing UTF-8 byte array; string decoded String = Encoding.UTF8.GetString(utf8Bytes); This will take the UTF-8 encoded byte array and decode it into a string that can be used within your C# application.

User Jlengrand
by
8.6k points