【问题标题】:Log file gets created but remains empty?日志文件已创建但仍为空?
【发布时间】:2014-07-09 18:23:53
【问题描述】:

我在我的 Windows 窗体应用程序中使用 log 方法实现了一个 Utility 类。它似乎可以很好地创建 log.txt 文件,但没有向其中写入任何内容。没有其他程序正在使用这个特定的文本文件。

using System;
using System.IO;
using System.Text;


namespace program1{
    static class Utils {

        static Utils() { }


        private static readonly string FilePath = TestEnvironment.PATH + @"\log.txt";

        private static void CheckFile()
        {
            if (File.Exists(FilePath)) return;

            using (FileStream fs = File.Create(FilePath)) {
                Byte[] info = new UTF8Encoding(true).GetBytes("");
                fs.Write(info, 0, info.Length);

                fs.Close();
            }

        }

        public static string Log(string code, string message) {

            StreamWriter _w = File.AppendText(FilePath);

            CheckFile();

            string log = ("\r\n" + code + ": \n");
            log += String.Format("{0} {1}\n", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            log += String.Format("  :{0}\n", message);
            log += String.Format("-------------------------------");
            _w.WriteLine(log);
            _w.Close();
            return log;
        }

        public static string LogDump() {

            StreamReader _r = File.OpenText(FilePath);
            string output = "";

            string line;
            while ((line = _r.ReadLine()) != null) {
                output += line;
            }
            _r.Close();

            return output;
        }



    }
}

它可能不喜欢 String.Formats 吗?

【问题讨论】:

  • 函数 Log() 返回的字符串是否正确?
  • Log 不会释放 StreamWriter 对象,因此不会将流刷新到磁盘,除非您写入足够长的消息来填充缓冲区。

标签: c# windows winforms logging


【解决方案1】:

根据MSDN

除非您显式调用 Flush 或处置对象,否则不会刷新流的编码器。

释放您正在创建的StreamWriter 实例(最好将其包含在using 块中,或者通过显式调用Dispose()):

using (StreamWriter _w = File.AppendText(FilePath))
{
    ...
}

或者显式调用Flush()

_w.Flush();

【讨论】:

    【解决方案2】:

    您不需要CheckFile() 方法。 AppendText() 将在必要时创建文件。

    真正的问题是您如何编写文件。将您的方法更改为:

    public static string Log(string code, string message)
    {
        string log;
        using (var writer = File.AppendText(FilePath))
        {
            log = ("\r\n" + code + ": \n");
            log += String.Format("{0} {1}\n", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            log += String.Format("  :{0}\n", message);
            log += String.Format("-------------------------------");
            writer.WriteLine(log);
        }
    
        return log;
    }
    

    为了澄清,using 块调用StreamWriter 上的Dispose()。这会将内容刷新到文件中。

    【讨论】:

    • 我们仍在使用 StreamWriter。 var 只是“自动输入”writerStreamWriter
    • 不会的,这里的真正的修复是using (...) { },你忘记处理StreamWriter对象了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2014-11-09
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多