【发布时间】: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