重用FILESTREAM [英] Reusing a filestream

查看:146
本文介绍了重用FILESTREAM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去,我一直使用FileStream对象编写或改写整个文件之后,我会立即关闭流。不过,现在我的工作中,我想保持一个FileStream打开,以允许用户,而他们的工作在省之间保留访问该文件的程序。 (见我以前问题)。

In the past I've always used a FileStream object to write or rewrite an entire file after which I would immediately close the stream. However, now I'm working on a program in which I want to keep a FileStream open in order to allow the user to retain access to the file while they are working in between saves. ( See my previous question).

我使用的XmlSerializer我从类和XML文件序列化到一个。但现在我保持FileStream打开被用来保存后(reserialized)我的类实例。有什么特别的考虑,我需要做,如果我一遍又一遍地重复使用相同的文件流,与使用一个新的文件流?我需要到流重置为节省之间的开始?如果以后保存在尺寸上比以前的小节省将离开的FileStream从旧文件其余字节,从而创建一个损坏的文件?我需要做一些事来清除文件,所以它的行为就好像我每次写一个全新的文件?

I'm using XmlSerializer to serialize my classes to a from and XML file. But now I'm keeping the FileStream open to be used to save (reserialized) my class instance later. Are there any special considerations I need to make if I'm reusing the same File Stream over and over again, versus using a new file stream? Do I need to reset the stream to the beginning between saves? If a later save is smaller in size than the previous save will the FileStream leave the remainder bytes from the old file, and thus create a corrupted file? Do I need to do something to clear the file so it will behave as if I'm writing an entirely new file each time?

推荐答案

您的怀疑是正确的 - 如果你重新设置一个打开的文件流的位置,写的内容,这比什么是已经在文件中较小的,会留下尾数据,并导致损坏的文件(取决于你的腐败的定义,当然)。

Your suspicion is correct - if you reset the position of an open file stream and write content that's smaller than what's already in the file, it will leave trailing data and result in a corrupt file (depending on your definition of "corrupt", of course).

如果你想覆盖文件,你真的应该关闭流,当你完成它,并创建一个新的流当你准备好重新保存。

If you want to overwrite the file, you really should close the stream when you're finished with it and create a new stream when you're ready to re-save.

我从你持有的文件打开,以防止其他用户在同一时间写就您的问题联系在一起通知。这可能不会是我的选择,但如果你要做到这一点,那么我的认为的可以清除通过调用文件 stream.SetLength(0)之间的连续扑救。

I notice from your linked question that you are holding the file open in order to prevent other users from writing to it at the same time. This probably wouldn't be my choice, but if you are going to do that, then I think you can "clear" the file by invoking stream.SetLength(0) between successive saves.

这篇关于重用FILESTREAM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆