I want to save some plain text periodically to a text file, and it will be really better if I can minimize the chance of corrupting the file in case the app gets terminated or the system restarts. What are the way to ensure that the plain text file is always good.
I will run the program from USB drive, so want to make sure the file is still perfect if I eject the drive without closing the App.
Do not use option FileMode.Create
, which overwrites existing files. Instead, use option FileMode.Append
when creating the file stream, so that any text will be appended to the file without modifying last data.
However, try not to keep the files opened for long period, just open them and read or write and then Dispose
them.
Use File. AppendAllText to open, append and close in one go.
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.