c#如何创建用户活动的日志?

时间:2014-04-04 20:05:44

标签: c# winforms logging

我创建了一个简单的应用程序来将文件从我的计算机复制到闪存驱动器,我希望有一个用户活动的日志。 喜欢: 启动和关闭应用程序的时间。 复制的文件夹或文件的路径以及目标的路径。 新创建的文件夹的时间和名称......等等。

我还没有尝试任何事情,因为我不知道该怎么做。

我需要将记录的数据转换为文本文件。我正在使用 Windows窗体

提前谢谢。

2 个答案:

答案 0 :(得分:2)

当我想要一个简单的文本文件日志时,我已经使用了类似的东西:

    static void LogThis(string logMessage)
    {
        Console.WriteLine(logMessage);
        using (StreamWriter writer = new StreamWriter(FileDate() + ".txt", true))
        {
            writer.WriteLine(logMessage);
            writer.WriteLine();
        }
    }

    static string FileDate()
    {
        return DateTime.Now.ToString("yyyy") + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("dd");
    }

用法:

LogThis("I'm logging this!");

答案 1 :(得分:1)

使用System.Diagnostics命名空间,使用事件日志:

来源:http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.110).aspx

if(!EventLog.SourceExists("MySource"))
    {
         //An event log source should not be created and immediately used. 
         //There is a latency time to enable the source, it should be created 
         //prior to executing the application that uses the source. 
         //Execute this sample a second time to use the new source.
        EventLog.CreateEventSource("MySource", "MyNewLog");
        Console.WriteLine("CreatedEventSource");
        Console.WriteLine("Exiting, execute the application a second time to use the source.");
        // The source is created.  Exit the application to allow it to be registered. 
        return;
    }

EventLog myLog = new EventLog();
    myLog.Source = "MySource";

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