简单的存放在log.txt文件中
using System;
using System.Collections.Generic;
using System.Text;
using System.Security .Permissions ;
using System.IO ;
namespace KKCatCore
{
public class Log
{
public string message
{ get; set; }
public DateTime date
{ get; set; }
public static List<Log> Data
{ get; set; }
static Log ()
{
if (!File.Exists(Settings.Default.logPath)) File.Create(Settings.Default.logPath);
FileIOPermission permission=new FileIOPermission (FileIOPermissionAccess .AllAccess ,Settings .Default .logPath );
permission .Demand ();
}
public Log(string message, DateTime date)
{
this.message = message;
this.date = date;
}
public static void Record(string message)
{
using (StreamWriter sw=new StreamWriter (Settings .Default .logPath ))
{
sw.WriteLine (message );
sw.WriteLine (DateTime .Now .ToLongTimeString());
sw.Close ();
}
}
public static List<Log> AllLogs()
{
using (StreamReader sr = File.OpenText(Settings.Default.logPath))
{
Data = new List<Log>();
while (!sr.EndOfStream)
{
Data.Add(new Log(sr.ReadLine(), DateTime.Parse(sr.ReadLine())));
}
Data.TrimExcess();
return Data;
}
}
public static string LastMessage()
{
string mess="No log";
DateTime dt = DateTime.MinValue;
foreach (Log l in Data)
{
if (l.date > dt)
{
mess = l.message;
dt = l.date;
}
}
return mess;
}
}
}
上面的版本中写入记录部分每次都会丢失原来的数据
下面是msdn的原文
using System;
using System.IO;
class DirAppend
{
public static void Main(String[] args)
{
using (StreamWriter w = File.AppendText("log.txt"))
{
Log ("Test1", w);
Log ("Test2", w);
// Close the writer and underlying file.
w.Close();
}
// Open and read the file.
using (StreamReader r = File.OpenText("log.txt"))
{
DumpLog (r);
}
}
public static void Log (String logMessage, TextWriter w)
{
w.Write("\r\nLog Entry : ");
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine ("-------------------------------");
// Update the underlying file.
w.Flush();
}
public static void DumpLog (StreamReader r)
{
// While not at the end of the file, read and write lines.
String line;
while ((line=r.ReadLine())!=null)
{
Console.WriteLine(line);
}
r.Close();
}
}