第一种效果图
界面就一个button,一个textbox,一个listbox
private object obj=new object();//锁
private string lastMessage;//记录上一条历史信息
private List<string> Messages=new List<string>();//信息集合
private void RecordMessage(string _message)
{
lock (obj)
{
lastMessage = _message;
string message = string.Format("[{0}]:{1}", DateTime.Now.ToString("HH:mm:ss"), _message);
if (Messages.Count == 0)//直接插入
{
Messages.Insert(0, message);
SaveMessage(message);
}
else
{
if (Messages.Count > 20) //默认信息框中最多显示20条
Messages.RemoveAt(Messages.Count - 1);
//查找头两条,是否有信息重复。存在重复,将时间刷新即可。不保存到配置文件。
int repeat = Messages.FindIndex(0, Messages.Count > 2 ? 2 : 1, t => t.Contains(_message));
if (repeat == -1)
{
Messages.Insert(0, message);
SaveMessage(message);
}
else
{
Messages.RemoveAt(repeat);
Messages.Insert(0, message);
}
}
//绑定到listbox中显示
listBox1.Items.Clear();
listBox1.Items.AddRange(Messages.ToArray());
}
}
/// <summary>
/// 保存到txt中
/// </summary>
/// <param name="message"></param>
private void SaveMessage(string message)
{
if (!Directory.Exists(Application.StartupPath + "\\" + DateTime.Now.Month + "月\\"))
Directory.CreateDirectory(Application.StartupPath + "\\" + DateTime.Now.Month + "月\\");
if (!Directory.Exists(Application.StartupPath + "\\" + DateTime.Now.Month + "月\\" + "测试保存\\"))
Directory.CreateDirectory(Application.StartupPath + "\\" + DateTime.Now.Month + "月\\" + "测试保存\\");
StreamWriter sw = new StreamWriter(Application.StartupPath + "\\" + DateTime.Now.Month + "月\\" + "测试保存\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, Encoding.Default);
sw.WriteLine(message);
sw.Flush();
sw.Close();
}
private void button1_Click(object sender, EventArgs e)
{
RecordMessage(textBox1.Text.Trim());
}
第二种通过异步线程直接记录
public class Logs
{
/// <summary>
/// 带String.Format写入
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public static void Write(string format, params object[] args)
{
Write(string.Format(format, args));
}
public static void Write(string text)
{
DoLog(text, string.Format("{0:yyyyMMdd}.error.txt", DateTime.Now));
}
/// <summary>
/// 异步写入日志
/// </summary>
/// <param name="text"></param>
/// <param name="filename"></param>
private static void DoLog(string text, string filename)
{
int thread = Thread.CurrentThread.ManagedThreadId;
Task task = new Task(() =>
{
try
{
string dir = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Log");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
using (StreamWriter sw = new StreamWriter(Path.Combine(dir, filename), true, Encoding.UTF8))
{
sw.WriteLine("[{0}] {1:HH:mm:ss.fff} {2}", thread.ToString().PadLeft(2), DateTime.Now, text);
}
}
catch (Exception) { }
});
task.Start();
}
}