Thursday, 8 August 2013

FileStream ReadWrite in C#

FileStream ReadWrite in C#

I have a FileStream open as follows:
FileInfo file = new FileInfo(@"C:\Project.xml");
FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite,
FileShare.None);
XmlDocument document = new XmlDocument();
document.Load(stream);
The stream is opened when a project file is loaded. Now I need to be able
to overwrite its contents when changes are saved. At this point, I have a
reference to the FileStream object which is kept open to prevent other
apps/users making changes to it.
What I don't understand is how the write method will work. The size of the
previous and new data may be different. So the following code does not
make sense.
stream.Position = 0;
document.Save(stream);
stream.Close();
How is it possible to overwrite the contents without closing the stream
and reopening it?

No comments:

Post a Comment