开发者

StreamWriter not creating new file

开发者 https://www.devze.com 2022-12-23 22:54 出处:网络
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 c

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 c开发者_JAVA百科reated. 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());
    }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号