1

In C# How can we convert byte[] to string with a charset.eg utf8,SHIFT_JIS,and more .I know Encoding.UTF8

byte[] inputBytes =SupportClass.ToByteArray(readBytes);
StringBuilder result;
result.Append(System.Text.Encoding.UTF8.GetString(inputBytes,0,inputBytes.Length));//get unreadable code.

my question is how can I get the result from inputBytes with a special charset,like java

StringBuffer result.append(new String(buffer, "SJIS"));

2 Answers 2

3
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("shift-jis");
result.Append(enc.GetString(inputBytes,0,inputBytes.Length));

See this article:

http://msdn.microsoft.com/en-us/library/aa332097(v=vs.71).aspx

3
  • Good answer,but when I use System.Text.Encoding.GetEncoding("GB18030"),it seems not fire.what's wrong,indeed encoding name "gb2312" is wantted,but in your linked page I can't find this encoding name; this puzzled me. Commented Mar 6, 2012 at 3:35
  • 1
    Both GB18030 and GB2312 can used with GetEncoding (msdn.microsoft.com/en-us/library/…) - please clarify what problem you are facing (potentially in a new question). Commented Mar 6, 2012 at 3:45
  • 1
    In wp7,gb2312 is not supportted! Commented Mar 9, 2012 at 2:31
1

Instead of Encoding.UTF8, use Encoding.GetEncoding.

E.g.

private static readonly Encoding SHIFT_JIS = Encoding.GetEncoding("Shift_JIS");

SHIFT_JIS.GetString(inputBytes,0,inputBytes.Length)

Not the answer you're looking for? Browse other questions tagged or ask your own question.