fearofawhackplanet
fearofawhackplanet

Reputation: 53388

StreamWriter not creating new file

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());
    }
}

Upvotes: 3

Views: 2435

Answers (4)

RvdK
RvdK

Reputation: 19790

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

Upvotes: 0

Paul Turner
Paul Turner

Reputation: 39625

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.

Upvotes: 0

Hexateron
Hexateron

Reputation: 11

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

Upvotes: 1

João Angelo
João Angelo

Reputation: 57678

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.

Upvotes: 6

Related Questions