StreamWriter does not create a new file

I try to create a new log file every hour with the following code running on the server. The first log file of the day is created and recorded, but no log files are created on that day. Any ideas what could go wrong? Exceptions are also not thrown.

private void LogMessage(Message msg)
{
    string name = _logDirectory + DateTime.Today.ToString("yyyyMMddHH") + ".txt";

    using (StreamWriter sw = File.AppendText(name))
    {
        sw.WriteLine(msg.ToString());
    }
}
+3
source share
4 answers

Use DateTime.Todayresets the temporary part. You must use DateTime.Nowor DateTime.UtcNowso that the return DateTimecontains an hour other than zero.

+6
source

. HH "00". DateTime.Now.ToString( "yyyyMMddHH" ).

+1

, - datetime.today. Path.Combine , , "/" .. MSDN

0

, , DateTime.Today DateTime.Now. DateTime.Today - , DateTime.Now, , (00:00).

DateTime.Now.ToString("yyyyMMddHH") "2010032211"

DateTime.Today.ToString("yyyyMMddHH") "201032200" ( )

In the case DateTime.Todayyou will see the same value, regardless of the time of day. That's why you only get the first file created, since your code will only create a unique file name every day, not every hour.

Change DateTime.Todayto DateTime.Nowand your problem will be solved.

0
source

Source: https://habr.com/ru/post/1738017/


All Articles