日期:2014-05-19  浏览次数:21377 次

C#的日志文件怎么写?
C#的日志文件怎么写?对写一个log不会用,也不会写!!!

------解决方案--------------------
是写事件日志还是就是一个文本文件?

事件日志:
使用EventLog 类,如:
下面的示例创建源 MySource(如果尚未存在),并在事件日志 MyNewLog 中写入一项。

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

public static void Main(){

// Create the source, if it does not already exist.
if(!EventLog.SourceExists( "MySource ")){
EventLog.CreateEventSource( "MySource ", "MyNewLog ");
Console.WriteLine( "CreatingEventSource ");
}

// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource ";

// Write an informational entry to the event log.
myLog.WriteEntry( "Writing to event log. ");

}
}


文本文件:
如下代码向一个文本文件写入字符内容
using System;
using System.IO;

class Test
{
public static void Main()
{
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter( "TestFile.txt "))
{
// Add some text to the file.
sw.Write( "This is the ");
sw.WriteLine( "header for the file. ");
sw.WriteLine( "------------------- ");
// Arbitrary objects can also be written to the file.
sw.Write( "The date is: ");
sw.WriteLine(DateTime.Now);
}
}
}