user705414
user705414

Reputation: 21220

How to convert a string to UTF8?

I have a string that contains some unicode, how do I convert it to UTF-8 encoding?

Upvotes: 11

Views: 91330

Answers (4)

Arvin
Arvin

Reputation: 1260

Try this function, this should fix it out-of-box. You may need to fix naming conventions though.

private string UnicodeToUTF8(string strFrom)
{
    byte[] bytSrc;
    byte[] bytDestination;
    string strTo = String.Empty;

    bytSrc = Encoding.Unicode.GetBytes(strFrom);
    bytDestination = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, bytSrc);
    strTo = Encoding.ASCII.GetString(bytDestination);

    return strTo;
}

Upvotes: 4

Habeeb
Habeeb

Reputation: 8017

This should be with the minimum code:

byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);

Upvotes: 3

Shyam sundar shah
Shyam sundar shah

Reputation: 2523

try to this code

 string unicodeString = "Quick brown fox";
 var bytes = new List<byte>(unicodeString);
        foreach (var c in unicodeString)
            bytes.Add((byte)c);
        var retValue = Encoding.UTF8.GetString(bytes.ToArray());

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

This snippet makes an array of bytes with your string encoded in UTF-8:

UTF8Encoding utf8 = new UTF8Encoding();
string unicodeString = "Quick brown fox";
byte[] encodedBytes = utf8.GetBytes(unicodeString);

Upvotes: 22

Related Questions