简体   繁体   English

StreamWriter只写第一行

[英]StreamWriter only writes first line

I have a C# .NET 3.5 Windows Form program with this method: 我有一个使用此方法的C#.NET 3.5 Windows Form程序:

    private void toLog(string sLog)
    {
        richTextBox1.Text += DateTime.Now.ToString("T") + ": " + sLog + "\n";
        richTextBox1.Update();
        richTextBox1.Refresh();
        using (StreamWriter writer = new StreamWriter("log.txt", true))
        {
            writer.WriteLine(DateTime.Now.ToString("T") + ": " + sLog);
            writer.Flush();
            writer.Dispose();
        }

    }

The idea is that I can submit log entries with it and it will write the entry to both the richtextbox and the log file. 我的想法是,我可以使用它提交日志条目,它将条目写入Richtextbox和日志文件。

Here's the thing... the streamwriter only writes the first time the method is called! 事情就是这样……流编写器仅在第一次调用该方法时编写! The richtextbox updates great. richtextbox更新非常好。 Flush() and Dispose() were something I tried later out of desperation, but I guess the using block should handle that. 我后来无奈地尝试了Flush()和Dispose(),但是我想using块应该可以解决这个问题。

Any ideas? 有任何想法吗? Thanks! 谢谢!

I think problem could be in StreamWriter("log.txt", : path could be changed inside your app, so you'd better to use full path here. 我认为问题可能出在StreamWriter("log.txt",可以在您的应用程序内部更改路径,因此您最好在此处使用完整路径。
Example: 例:

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string log = Path.Combine(dir, "log.txt");
using (StreamWriter writer = new StreamWriter(log, true))

I know I'm late to the party, but this helped me with a similar situation and maybe it'll help someone else. 我知道我参加晚会很晚,但这在类似情况下对我有所帮助,也许会对其他人有所帮助。

I was having the same problem where the streamwriter was only writing the first line in the file and nothing else. 我遇到了同样的问题,即流编写器只写文件的第一行,什么也没写。 I was able to fix it by using a FileStream: 我可以使用FileStream修复它:

using (FileStream fileStream = File.Open("log.txt", FileMode.Open))
{
    using (StreamWriter streamWriter= new StreamWriter(fileStream))
    { 
        writer.WriteLine(DateTime.Now.ToString("T") + ": " + sLog);
    }
}

You can use the example below: 您可以使用以下示例:

using (StreamWriter writer = File.AppendText("log.txt")) 
{
    writer.WriteLine(DateTime.Now.ToString("T") + ": " + sLog);
}   

The Flush and Dispose are not necessary to use at the end of the using block, because the will be implicity called. 在using块的末尾不需要使用Flush和Dispose,因为将隐式调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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