views:

196

answers:

4

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());
    }
}
+5  A: 

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.

João Angelo
He uses DateTime.Today to create file with that name. Using DateTime.Now for file name makes no sense since he want to reuse the file for current day.
MadBoy
@MadBoy, from the OP question: ("I'm trying to create a new log file every hour"). The returned `DateTime` is then formatted to contain only the date and hour component.
João Angelo
d'oh! thanks JA. *hangs head in shame*
fearofawhackplanet
@Joao Angelo: sorry, I've misread then. Thought he wanted to append to log, and not create new one every time.
MadBoy
A: 

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

PoweRoy
+1  A: 

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

Hexateron
A: 

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.

Programming Hero