this snippet should be fairly self-explanatory:
XDocument xd = ....
using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite))
{
using (TextWriter tw = new StreamWriter(fs))
{
xd.Save(tw);
}
fs.Flush();
fs.SetLength(fs.Position);
}
I want to serialize my XDocument to a stream using a TextWriter and then truncate the stream after the end of it. Unfortunately, the Save() operation seems to close the stream so my Flush() call generates an Exception.
In the real world, I’m not actually serializing to a file but some other kind of stream outside my control, so it’s not a simple as just deleting the file first.
you need to do this if you want to flush the stream