.net 为什么我会得到一个XmlException;意外的文件结尾“;使用TextMessageEncodingBindingElement?

.net 为什么我会得到一个XmlException;意外的文件结尾“;使用TextMessageEncodingBindingElement?,.net,wcf,.net,Wcf,我尝试做一些理论上非常简单的事情:将字符串反序列化为消息,下面是代码: [TestMethod] public void EncoderErrorTest() { var message = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\"><s:Header><a:Action s

我尝试做一些理论上非常简单的事情:将字符串反序列化为消息,下面是代码:

[TestMethod]
public void EncoderErrorTest()
{
    var message = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\"><s:Header><a:Action s:mustUnderstand=\"1\">http://tempuri.org/IHelloWorldService/SayHello</a:Action></s:Header><s:Body><SayHello xmlns=\"http://tempuri.org/\"><name>Nico</name></SayHello></s:Body></s:Envelope>";

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(message);
    stream.Position = 0;
    var soapMessage = new TextMessageEncodingBindingElement().CreateMessageEncoderFactory().Encoder.ReadMessage(stream, 99999);
    Assert.IsNotNull(soapMessage);
}
[TestMethod]
公共无效编码器错误测试()
{
var消息=”http://tempuri.org/IHelloWorldService/SayHelloNico";
MemoryStream stream=新的MemoryStream();
StreamWriter writer=新StreamWriter(流);
写(信息);
流位置=0;
var soapMessage=new TextMessageEncodingBindingElement().CreateMessageEncoderFactory().Encoder.ReadMessage(stream,99999);
Assert.IsNotNull(soapMessage);
}
但是在反序列化过程中,我得到了一个XmlException“意外的文件结尾”。 我的代码有问题吗


提前感谢您的回复。

在读取流之前,请尝试在
StreamWriter
上调用
Flush
(或者更好的是,使用
-block将其放入
中)。

据我所知,MemoryStream
不是缓存(这将是毫无意义的,为什么要为内存备份的流进行内存缓存?),但这不会有什么坏处,“使用块”规则的例外越少越好。