我有一个具有AutoFlush = true属性的StreamWriter。然而,当我随机打开它时,我仍然看到文件只写了一部分。我正在编写一个在任何给定时间都需要完全写入(JSON)或不完全写入的文件。
var sw = new StreamWriter("C:\file.txt", true /* append */, Encoding.ASCII) { AutoFlush = true };
sw.WriteLine("....");
// long running (think like a logging application) -- 1000s of seconds
sw.Close();在sw.WriteLine()调用和sw.Close()调用之间,我希望打开文件,并始终使其采用“正确的数据格式”,即我的行应该是完整的。
当前的想法:
将FileStream (和/或StreamWriter)的内部缓冲区增加到128KB。然后,每隔128KB-1,对FileStream对象调用.Flush()。这就引出了我的下一个问题,当我调用Flush()时,我是否应该在调用它之前获取Stream.Position并执行File.Lock(位置,128KB-1)?还是说同花顺能解决这个问题呢?
基本上,我不希望阅读器能够读取Flush()之间的内容,因为它可能会部分损坏。
发布于 2014-03-30 04:05:12
using (StreamWriter sw = new StreamWriter("FILEPATH"))
{
sw.WriteLine("contents");
// if you open the file now, you may see partially written lines
// since the sw is still working on it.
}
// access the file now, since the stream writer has been properly closed and disposed.发布于 2018-12-10 17:57:53
如果你需要一个永远不会半途而废的“类似日志”的文件,最好的办法就是不让它保持打开状态。
每次要写文件时,都应该实例化一个新的FileWriter,它将在释放文件时刷新文件内容,如下所示:
private void LogLikeWrite(string filePath, string contents)
{
using (StreamWriter streamWriter = new StreamWriter(filePath, true)) // the true will make you append to the file instead of overwriting its contents
{
streamWriter.Write(contents);
}
}这样,您的写入操作将立即刷新。
发布于 2018-12-15 07:57:33
如果你在进程之间共享文件,除非你产生某种类型的锁定机制,否则你将会有一个竞争条件。参见https://stackoverflow.com/a/29127380/892327。这确实要求您能够修改这两个进程。
另一种方法是让进程A在指定位置等待文件。进程B写入一个中间文件,一旦B被刷新,该文件就被复制到进程A期望的位置,以便它可以使用该文件。
https://stackoverflow.com/questions/22735797
复制相似问题