2014/07/29

How to convert encoding from one to another in C# ?

public static string ChangeEncoding(Encoding encFrom, Encoding encTo, string srcStr)
{
// Convert the string into a byte[].
byte[] fromBytes = encFrom.GetBytes(srcStr);
// Perform the conversion from one encoding to the other.
byte[] toBytes = Encoding.Convert(encFrom, encTo, fromBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] toChars = new char[encTo.GetCharCount(toBytes, 0, toBytes.Length)];
encTo.GetChars(toBytes, 0, toBytes.Length, toChars, 0);
return new string(toChars);
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment