简体   繁体   中英

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? 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM