简体   繁体   English

C#中的FileStream ReadWrite

[英]FileStream ReadWrite in C#

I have a FileStream open as follows: 我有一个FileStream打开如下:

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. 此时,我有一个FileStream对象的引用,该对象保持打开状态以防止其他应用程序/用户对其进行更改。

What I don't understand is how the write method will work. 我不明白的是write方法是如何工作的。 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() . 如果没有,您可以通过调用stream.SetLength()来截断该文件。
You would want to set it to stream.Position , which indicates how many bytes have been written so far. 您可能希望将其设置为stream.Position ,它指示到目前为止已写入的字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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