[英]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());
}
}
The use of DateTime.Today
zeroes the time part. 使用
DateTime.Today
将时间部分归零。 You should use DateTime.Now
or DateTime.UtcNow
so that the returned DateTime
contains an hour different than zero. 您应该使用
DateTime.Now
或DateTime.UtcNow
以便返回的DateTime
包含一个不同于零的小时。
Today only gives the current date. 今天仅给出当前日期。 So HH is always "00".
因此,HH始终为“ 00”。 Try DateTime.Now.ToString("yyyyMMddHH") instead.
请尝试使用DateTime.Now.ToString(“ yyyyMMddHH”)。
The reason you're only getting one file is due to your use of DateTime.Today
instead of DateTime.Now
. 之所以只能得到一个文件,是因为您使用了
DateTime.Today
而不是DateTime.Now
。 DateTime.Today
is the same value as DateTime.Now
, but with the time element set to midnight (00:00). DateTime.Today
是相同的值DateTime.Now
,但随着时间元件设置为午夜(00:00)。
DateTime.Now.ToString("yyyyMMddHH")
produces "2010032211" DateTime.Now.ToString("yyyyMMddHH")
产生“ 2010032211”
DateTime.Today.ToString("yyyyMMddHH")
produces "201032200" (no time part) DateTime.Today.ToString("yyyyMMddHH")
产生“ 201032200”(无时间部分)
In the case of DateTime.Today
, you will see the same value, regardless of the time of day. 对于
DateTime.Today
,无论一天中的什么时间,您都将看到相同的值。 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. 将
DateTime.Now
更改为DateTime.Today
即可解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.