使用C#将动态变量保存在文本文件中而不关闭它

Save dynamic variables in text file without closing it using C#

我需要尽快将六个动态变量保存在一个文本文件中,如果电源关闭(或应用程序被终止),我可以访问所有变量的最后保存版本在一起(不仅仅是一些变量)。

在注册表中写入这六个变量需要 ~0.1 ms,这很好。但是我宁愿避免修改注册表。

我在 backgroundworker 循环中试过 StreamWriter 这样的:

System.IO.StreamWriter file = new System.IO.StreamWriter("test.txt", false);
file.Write("Comma Separated Version of Variables in String");
file.Flush();
file.Close();

它比 1 ms 花费更多,这对我的应用程序来说很慢!所以,我从循环中删除了第一行和最后一行:

System.IO.StreamWriter file = new System.IO.StreamWriter("test.txt", false);
while (true)
{  
   file.Write("Comma Separated Version of Variables in String");
   file.Flush();
}
file.Close();

现在很棒(~0.007 ms)!但是,它将新字符串附加到文件中。如何在不关闭文本文件的情况下覆盖文本文件的第一行(它只有一行)?

编辑:我也试过 WriteAllText 这有效,但它比上面的代码慢了 15 倍!

将流的位置设置为 0。

while (true)
{
    file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
    file.WriteLine("Comma Separated Version of Variables in String");
    file.Flush();
}