Close a filestream without Flush()

后端 未结 7 2047
猫巷女王i
猫巷女王i 2021-01-03 20:42

Can I close a file stream without calling Flush (in C#)? I understood that Close and Dispose calls the Flush method first.

7条回答
  •  猫巷女王i
    2021-01-03 21:33

    Since you've stated that you understood that close & dispose called the flush method if it was not called explicitly by user code, I believe that (by close without flush) you actually want to have a possibility to discard changes made to a FileStream, if necessary.

    If that is correct, using a FileStream alone won't help. You will need to load this file into a MemoryStream (or an array, depending on how you modify its contents), and then decide whether you want to save changes or not after you're done.

    A problem with this is file size, obviously. FileStream uses limited size write buffers to speed up operations, but once they are depleted, changes need to be flushed. Due to .NET memory limits, you can only expect to load smaller files in memory, if you need to hold them entirely.

    An easier alternative would be to make a disk copy of your file, and work on it using a plain FileStream. When finished, if you need to discard changes, simply delete the temporary file, otherwise replace the original with a modified copy.

提交回复
热议问题