0

我有一个正在处理的新项目,它使用 TextWriter 对象来序列化一个类。像这样的东西:

TextWriter txtStream = new StreamWriter("xmlStreamFile.xml");
xmlSel.Serialize(txtStream, gp); // gp is the class I want to serialize
txtStream.Flush();
txtStream.Close(); 

这段代码在我第一次使用时有效 - 文件已创建并且数据写入正常 - 但我第二次尝试使用它时出现异常:“无法写入 ca 已关闭的 TextWriter”。我只是想问我如何重新打开 TextWriter - 或者我应该怎么做才能得到这种类型的异常并能够重写 txtStream 对象。谢谢!

4

3 回答 3

2

不,您不能重新打开 TextWriter 之类的东西,因为在一般情况下,它可能正在写入 NetworkStream 或 GZipStream 之类的东西 - 在这些情况下,当您关闭写入器(和流)时,它会产生副作用(终止网络连接,编写最终的 gzip 块等)。所以不:你不能那样做。

由于您正在写入文件,因此:

  • 在你准备好之前不要关闭它
  • 需要时重新打开文件(用于追加)
于 2012-04-08T09:26:27.600 回答
1

TextWriter最直接的答案是每次都重新打开一个新的。

public static void SerializeAsXml(object gp, string target)
{
    XmlSerializer xmlSel = new XmlSerializer(gp.GetType());
    using (TextWriter txtStream = new StreamWriter(target))
        xmlSel.Serialize(txtStream, gp);
}

using语句隐含地导致FlushClose在您的txtStream.

于 2012-04-08T08:47:59.643 回答
0

If you want to append to the same file, just use the same TextWriter and close it when you're done:

XmlSerializer xmlSel = new XmlSerializer(typeof(Foo));
TextWriter txtStream = new StreamWriter("xmlStreamFile.xml");
for (int i = 1; i <= 3; i++)
{
    Foo foo = new Foo(i * 100);
    xmlSel.Serialize(txtStream, foo);
    Console.WriteLine("Serialize done #" + i);
    txtStream.Flush();
}
txtStream.Close();
txtStream.Dispose();

In this sample Foo is just a simple struct, but it would work with your class as well.

Edit: assuming you're using WinForms you can have the XmlSerializer and StreamWriter members of the class itself:

class Form1 : Form
{
    private XmlSerializer xmlSel = null;
    TextWriter txtStream = null;
    //....
}

Then in the button click method initialize them once if null and serialize what you need:

if (xmlSel == null)
{
    xmlSel = new XmlSerializer(typeof(Foo));
    txtStream = new StreamWriter("xmlStreamFile.xml");
}
xmlSel.Serialize(txtStream, foo);
txtStream.Flush();

And finally in the Form close event, close and dispose the writer:

txtStream.Close();
txtStream.Dispose();
于 2012-04-08T09:06:41.407 回答