保持文件打开,不要在应用程序崩溃时丢失数据

Ars*_*ray 3 c# filestream

我需要将信息记录到文件大约每分钟1000-2000次.我还需要保存该信息以防应用程序崩溃.

目前这就是我正在做的事情:

using(StreamWriter sw=new StreamWriter(filename,true))
{
    sw.WriteLine(info);
}
Run Code Online (Sandbox Code Playgroud)

这有效,但速度极慢.

我想做这样的事情:

static StreamWriter sw=new StreamWriter(file,true);

....

public static void Main(...)
{
    .....
    sw.WriteLine(....);
}
Run Code Online (Sandbox Code Playgroud)

但是当我编写这样的代码时,我担心当应用程序崩溃时,我存储的信息会丢失.

如何保存文件中的信息而不必一直打开和关闭它?

Mat*_*son 5

你可以StreamWriter.Flush()在每次写作后打电话.

public static void Main(...)
{
    .....
    sw.WriteLine(....);
    sw.Flush();
}
Run Code Online (Sandbox Code Playgroud)

但是你应该使用NLogLog4Net!