简体   繁体   中英

Save text to file periodically

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.

Edit

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.

您可以看一下在NTFS文件系统上使用事务的情况 ,假设USB记忆棒已格式化为NTFS,并且您的操作系统为Vista或更高版本。

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