Zaid_Code36
Zaid_Code36

Reputation: 21

c# How to create a log of a user activities?

I have created a simple application to copy files from my computer to a flash drive and I would like to have a log of the user activities. like: The time of starting and closing the application. The path of the copied folder or file and the path of the destination. The time and the name of a newly created folder...etc.

I did not try any thing yet because I have no idea on how to do so.

I need to but the logged data into a text file. And I am using Windows Forms

Thank you in advance.

Upvotes: 1

Views: 8319

Answers (2)

safetyOtter
safetyOtter

Reputation: 1460

I've used something like this for when I want a simple text file log:

    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");
    }

Usage:

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

Upvotes: 1

T McKeown
T McKeown

Reputation: 12847

Using the System.Diagnostics namespace, use the event Log:

Source: 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.");

Upvotes: 1

Related Questions