StreamWriter won't write to log file

血红的双手。 提交于 2020-01-06 08:38:17

问题


This code will create "output.txt" in C:\temp if it doesn't already exist. However, log.WriteLine(); doesn't work for me. When I open the file, I don't see it. Why is this?

private static string LogFile = @"C:\Temp\output.txt";
private StreamWriter log;
if (!File.Exists(@"" + LogFile))
{
    log = new StreamWriter(@"" + LogFile);
}
else {
    log = File.AppendText(@"" + LogFile);
}
log.WriteLine("["+DateTime.Now + "]: ");

回答1:


You need to close the StreamWriter. It's best to use a using block for this, as it guarantees that the StreamWriter will be closed, even if an exception is thrown.

using (var log = GetLog()){
    log.WriteLine("["+DateTime.Now + "]: ");
}

...

public StreamWriter GetLog(){
    if (!File.Exists(@"" + LogFile))
    {
        return new StreamWriter(@"" + LogFile);
    }
    else {
        return File.AppendText(@"" + LogFile);
    }
}



回答2:


Just a little improvement in code to @John Saunders answer.

using (var log = GetLog())
{
    log.WriteLine("["+DateTime.Now + "]: ");
}

...

public StreamWriter GetLog()
{
    return new StreamWriter(LogFile, File.Exists(LogFile));
}

The second parameter StreamWriter constructer takes determines append operation. Thus if file exists append otherwise not will do it. I think this is neater. And actually you can even do:

using (var log = new StreamWriter(LogFile, true))
{
    log.WriteLine("["+DateTime.Now + "]: ");
}

Always appends, and if file does not exist creates it.




回答3:


If you are always appending the same thing to the file whether or not it already exists, you don't need the conditional.

File.AppendText will create the file if it doesn't exist.

private static string LogFile = @"C:\Temp\output.txt";

using (StreamWriter sw = File.AppendText(LogFile)) 
{
    sw.WriteLine("["+DateTime.Now + "]: ");
}

As John Saunders already said, you need to Dispose the stream writer, which will be done by putting it in a using statement.

(Documentation for StreamWriter)



来源:https://stackoverflow.com/questions/22853262/streamwriter-wont-write-to-log-file

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