StreamWriter not creating new file

安稳与你 提交于 2019-12-10 17:46:59

问题


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

回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2491729/streamwriter-not-creating-new-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!