简体   繁体   English

定期将文本保存到文件

[英]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. 我将从USB驱动器运行该程序,因此,如果我在不关闭应用程序的情况下弹出驱动器,则要确保文件仍然是完美的。

Do not use option FileMode.Create , which overwrites existing files. 不要使用选项FileMode.Create ,它会覆盖现有文件。 Instead, use option FileMode.Append when creating the file stream, so that any text will be appended to the file without modifying last data. 而是在创建文件流时使用选项FileMode.Append ,以便将任何文本添加到文件中,而无需修改最后一个数据。

However, try not to keep the files opened for long period, just open them and read or write and then Dispose them. 但是,请尽量不要长时间打开文件,只是打开它们并对其进行读写,然后再Dispose它们。

Use File. 使用文件。 AppendAllText to open, append and close in one go. AppendAllText可一次打开,追加和关闭。

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

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

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