This is a small blog of Code Access and Security in c#. In this blog we try to know status of user or we can say how we can know that the user who is login is administrator or user or guest and what is account name.
For performing this task we used to import using System.Security.Principal namespace and we used two classes which WindowsIdentity and WindowsPrincipal class.
Following example demonstrate that how to use these classes to know user status information in c#.net.
using System;
using System.Security.Principal; //This name space is required for using WindowsIdentity and WindowsPrinciple class.
namespace UserTypeDemo
{
class Program
{
static void Main(string[] args)
{
//Create an object of WindowsIdentity class using GetCurrent() method of WindowsIdentity class.
WindowsIdentity identity = WindowsIdentity.GetCurrent();
//Create an object of windows principle class using new keyword and pass WindowsIndentity object
//As parameter to constructor of WindowPrinciple class.
WindowsPrincipal principle = new WindowsPrincipal(identity);
//Display current user login name.
Console.WriteLine("Current Login User Name : {0}", principle.Identity.Name);
//Display type of user such as he is admin, guest or user.
if (principle.IsInRole(WindowsBuiltInRole.AccountOperator))
Console.WriteLine("Login User is : Account Operator.");
else
if (principle.IsInRole(WindowsBuiltInRole.Administrator))
Console.WriteLine("Login User is : Administrator.");
else
if (principle.IsInRole(WindowsBuiltInRole.BackupOperator))
Console.WriteLine("Login User is : Backup opearator.");
else
if (principle.IsInRole(WindowsBuiltInRole.Guest))
Console.WriteLine("Login User is : Guest.");
else
if (principle.IsInRole(WindowsBuiltInRole.PowerUser))
Console.WriteLine("Login User is : Power User.");
else
if (principle.IsInRole(WindowsBuiltInRole.User))
Console.WriteLine("Login User is : User.");
}
}
}
Output of the following code snippets is as follows:
Current Login User Name: abs-user.
Login User is: User.
Press any key to continue . . .
Anonymous User
25-Mar-2019Thank You.
Sunil Singh
10-Jul-2017Keep sharing these types of articles.