StreamWriter 不创建新文件
我试图每小时创建一个新的日志文件,并在服务器上运行以下代码。当天的第一个日志文件正在创建并写入正常,但当天没有创建更多日志文件。有什么想法可能会出问题吗?也不会抛出任何异常。
private void LogMessage(Message msg)
{
string name = _logDirectory + DateTime.Today.ToString("yyyyMMddHH") + ".txt";
using (StreamWriter sw = File.AppendText(name))
{
sw.WriteLine(msg.ToString());
}
}
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());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
DateTime.Today
将时间部分归零。您应该使用DateTime.Now
或DateTime.UtcNow
,以便返回的DateTime
包含不为零的小时。The use of
DateTime.Today
zeroes the time part. You should useDateTime.Now
orDateTime.UtcNow
so that the returnedDateTime
contains an hour different than zero.今天仅给出当前日期。所以 HH 始终为“00”。
请尝试使用 DateTime.Now.ToString("yyyyMMddHH") 代替。
Today only gives the current date. So HH is always "00".
Try DateTime.Now.ToString("yyyyMMddHH") instead.
您只获得一个文件的原因是您使用了
DateTime.Today
而不是DateTime.Now
。DateTime.Today
与DateTime.Now
的值相同,但时间元素设置为午夜 (00:00)。DateTime.Now.ToString("yyyyMMddHH")
生成“2010032211”DateTime.Today.ToString("yyyyMMddHH")
生成“201032200”(无时间部分)在这种情况下
DateTime.Today
的值,无论一天中的什么时间,您都会看到相同的值。这就是为什么您只获得创建的第一个文件,因为您的代码目前只会每天而不是每小时创建一个唯一的文件名。将
DateTime.Today
更改为DateTime.Now
即可解决您的问题。The reason you're only getting one file is due to your use of
DateTime.Today
instead ofDateTime.Now
.DateTime.Today
is the same value asDateTime.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
toDateTime.Now
and your problem is solved.由于 datetime.today 的使用,您的路径似乎不正确。
尝试在功能中使用 Path.Combine 来防止其他错误,例如“/”添加等 MSDN
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