我在Windows窗体应用程序中使用日志方法实现了一个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吗?
答案 0 :(得分:3)
根据MSDN:
除非您明确调用Flush或处置对象,否则不会刷新流的编码器。
处理您正在创建的StreamWriter
个实例(理想情况下将其封装在using
块中,或者通过显式调用Dispose()
):
using (StreamWriter _w = File.AppendText(FilePath))
{
...
}
或明确致电Flush()
:
_w.Flush();
答案 1 :(得分: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
阻止了Dispose()
上的StreamWriter
。这会将内容刷新到文件中。