Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the file open, don't lose data when the app crashes

Tags:

c#

filestream

I need to log info to a file around 1000-2000 times a minute. I also need to save that info in case the app crashes.

Currently here's what I'm doing:

using(StreamWriter sw=new StreamWriter(filename,true))
{
    sw.WriteLine(info);
}

This works, but it's extremely slow.

I'd like to be doing something like this:

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

....

public static void Main(...)
{
    .....
    sw.WriteLine(....);
}

but when I write code like this, I'm afraid that the info I store will get lost when the app crashes.

What can I do to preserve info in the file without having to open and close it all the time?

like image 756
Arsen Zahray Avatar asked Mar 23 '23 23:03

Arsen Zahray


1 Answers

You can call StreamWriter.Flush() after each write.

public static void Main(...)
{
    .....
    sw.WriteLine(....);
    sw.Flush();
}

But you should use NLog or Log4Net!

like image 101
Matthew Watson Avatar answered Apr 06 '23 17:04

Matthew Watson