9

Can someone please explain me what is the difference bet. Encoding.UTF8.GetBytes and UTF8Encoding.Default.GetBytes? Actually I am trying to convert a XML string into a stream object and what happens now is whenever I use this line:

  MemoryStream stream = new MemoryStream(UTF8Encoding.Default.GetBytes(xml));

it gives me an error "System.Xml.XmlException: Invalid character in the given encoding"

but when I use this line it works fine:

  **MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));**

Even though it seems to be UTF8 encoding in both cases how one works and the other does not?

4

1 回答 1

15

没有UTF8Encoding.Default财产。编写此代码时,您实际上返回的是基类静态属性 ,Encoding.Default它不是 UTF8(它是系统的默认 ANSI 代码页编码)。

因此,两者将返回非常不同的结果 - 因为UTF8Encoding.Default实际上是Encoding.Default,您将返回与使用ASCIIEncoding.Default或任何其他System.Text.Encoding子类相同的东西。

正确的使用方法UTF8Encoding是使用您创建的实例,例如:

MemoryStream stream = new MemoryStream((new UTF8Encoding()).GetBytes(xml));

以上应提供与以下相同的结果:

MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
于 2013-06-07T22:52:49.113 回答