Question

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? It seems illogical and if it is, how can I ensure that the file does not get locked by something else during the short time between closing and reopening the stream?

Was it helpful?

Solution

If the new document is longer than the old one, the file (and stream) will automatically expand.

If not, you can truncate the file by calling stream.SetLength().
You would want to set it to stream.Position, which indicates how many bytes have been written so far.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top