Sunday, April 5, 2020

Record System Log in and Log off Time using C#.

In this blog we are going to write a small Console Application using .Net core to record Write Date and time whenever the program is run and configure it using windows task scheduler to run during system login and logoff.



 Step 1: Create new Dotnet Core Console Application and name the application as “LogonTimeRecorderConsole” then paste the following code in the “Program.cs”.


using System;
using System.IO;

namespace LogonTimeRecorderConsole
{
    class Program
    {
        static void Main(string[] args)
        {
             
            string sPath = AppDomain.CurrentDomain.BaseDirectory.ToString();
            sPath = sPath + @"LogonTimeRecorderConsole.txt";

            if (!File.Exists(sPath))
            {
                using (File.Create(sPath)) { }
                File.WriteAllText(sPath, args[0] + DateTime.Now.ToString() + "\n");
            }
            else
            {
                File.AppendAllText(sPath, args[0] + DateTime.Now.ToString() + "\n");
            }

            Environment.Exit(0);

        }
    }
}

Step 2: Then Publish your Console Application. When you open your published folder you can see following files.


 Step 3: Open windows Task Scheduler. Goto Start type “Windows Task Scheduler”.


Step 4: Now we are going to use same console Application to a two task on for Recording Lockin Time and LockOut Time.Once the Task Scheduler is open.Click on Create Task.


 Step 5: In the Create Task Dialog give name and Description for the task.


 Step 6: Click on Triggers Tab. Click on New Button and Select “On WorkStation Lock” from the “Begin the Task” DropDown. And the Click ok.


Step 7: Once Trigger are set Successfully Click on Action Method. Click the Browser button and Select you program we created in the add Arguments Text Type “Login Time:”and Click Ok.


Step 8: In the Conditions Tab “Check” Wake the Computer to run this task.


Step 9: On Settings Tab “Check” Run a task as soon as possible after a schedule start missed and click ok.


Step 10: Once Every step is done you can see you task on Task Scheduler.


Follow the Same Step to Create Logoff Timer Task task. You need to change Two things for Logoff Timer. In the Trigger Settings Select “On Workstation unlock” under “Begin the Task” drop down.


In the Action Tab Type “Log Off Time:” in the Add arguments textbox.

If you created a task correctly in the task scheduler you can see "LogonTimeRecorderConsole.txt" file in the publish folder recording logoff and login time.

If you have queries write in comments section.  







No comments:

Post a Comment