Question

I'm trying to create a new log file every hour with the following code running on a server. The first log file of the day is being created and written to fine, but no further log files that day get created. Any ideas what might be going wrong? No exceptions are thrown either.

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

    using (StreamWriter sw = File.AppendText(name))
    {
        sw.WriteLine(msg.ToString());
    }
}
Was it helpful?

Solution

The use of DateTime.Today zeroes the time part. You should use DateTime.Now or DateTime.UtcNow so that the returned DateTime contains an hour different than zero.

OTHER TIPS

Today only gives the current date. So HH is always "00". Try DateTime.Now.ToString("yyyyMMddHH") instead.

The reason you're only getting one file is due to your use of DateTime.Today instead of DateTime.Now. DateTime.Today is the same value as DateTime.Now, but with the time element set to midnight (00:00).

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

DateTime.Today.ToString("yyyyMMddHH") produces "201032200" (no time part)

In the case of DateTime.Today, you will see the same value, regardless of the time of day. This is why you are getting only the first file created, as your code will currently only create a unique file name every day, rather than every hour.

Change DateTime.Today to DateTime.Now and your problem is solved.

It appears your path was incorrect due the datetime.today usage. Try to use Path.Combine in the feature to prevent other errors like '/' adding etc MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top