流不可读错误

时间:2011-03-22 20:28:25

标签: c# xml-serialization memorystream

我在声明中收到消息“Stream is not readable”

using (StreamReader sr = new StreamReader(ms))

我已经尝试过这里发布的提示但没有成功。谢谢您的帮助。

这是我的代码:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Conflict));
//Serialize Conflicts array to memorystream as XML
using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms))
    {
        foreach (Conflict ct in Conflicts)      
            xmlSerializer.Serialize(sw, ct);

        sw.Flush(); //Site tip
        ms.Position = 0;  //Site tip
    }
    //Retrieve memory stream to string
    using (StreamReader sr = new StreamReader(ms))
    {
        string conflictXml = String.Format(CultureInfo.InvariantCulture, "{0}</NewDataSet>",

2 个答案:

答案 0 :(得分:19)

当这段代码完成时,它还会处理附加的MemoryStream

using (StreamWriter sw = new StreamWriter(ms))
{
    foreach (Conflict ct in Conflicts)
        xmlSerializer.Serialize(sw, ct);
    sw.Flush(); //Site tip
    ms.Position = 0;  //Site tip
}

删除using语句,并在完成后手动处理流

StreamWriter sw = new StreamWriter(ms);

foreach (Conflict ct in Conflicts)
    xmlSerializer.Serialize(sw, ct);
sw.Flush(); //Site tip
ms.Position = 0;  //Site tip

// other code that uses MemoryStream here...

sw.Dispose();

答案 1 :(得分:2)

请尝试此操作(假设冲突类型为List<Conflict>):

XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Conflict>));
StringWriter sw = new StringWriter();
xmlSerializer.Serialize(sw, Conflicts);
string conflictXml = sw.GetStringBuilder().ToString();