Posted by : Deepak Vasudevan Thursday, September 20, 2012

In Linux we have an elegant and quick command to display the currently logged on user. It is called 'WhoAmI'. You can check out the manpage of this command here. I just thought would create a quick and simple C# port of the same and share it with interested users.

The code is a very simple and straight-forward console application and I hope it is also useful for beginners to learn the programming language with ease and fun.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;

namespace LavanyaDeepak.UnixCommands
{
    class WhoAmI
    {
        static void Main(string[] args)
        {
            Console.Clear();

            try
            {
                Console.ForegroundColor = ConsoleColor.Green;
                WindowsIdentity objWindowsIdentity = WindowsIdentity.GetCurrent();
                Console.WriteLine(string.Format("You are currently logged on as {0}", objWindowsIdentity.Name));
            }
            catch (System.Security.SecurityException objSecurityException)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine(string.Format("Could not fetch currently logged on user. There was a security error: ", objSecurityException.Message));
            }
            catch (System.Exception objGeneralException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("Could not fetch currently logged on user. There was a general error: ", objGeneralException.Message));
            }

            Console.ReadKey();
        }
    }
}

Popular Post

Blogger templates

Labels

Blog Archive

Followers

Blog Archive

Powered by Blogger.

- Copyright © Lavanya Deepak -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -