简体   繁体   English

StreamWriter没有创建新文件

[英]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.NowDateTime.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”)。

It appears your path was incorrect due the datetime.today usage. 由于datetime.today的使用,您的路径似乎不正确。 Try to use Path.Combine in the feature to prevent other errors like '/' adding etc MSDN 尝试在功能中使用Path.Combine以防止其他错误,例如'/'添加等MSDN

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM