目录
1. 用户账户名称 - 使用Environment类
使用Environment可以返回当前系统环境的一些常用信息,其中包括用户账户名称,则不需要额外使用System.Security.Principal中的类。
//用户名
Console.WriteLine(Environment.UserName);
//计算机NetBIOS名称
Console.WriteLine(Environment.MachineName);
//计算机网络域名称
Console.WriteLine(Environment.UserDomainName);
这是我的电脑的相应信息:
Mgen
MGEN-PC
Mgen-PC
这些信息也可以在计算机属性中查看:
2. 用户账户信息 - 使用WindowsIdentity和IdentityReference
System.Security.Principal.IIdentity接口是用来定义标识对象的基本功能,其派生类WindowsIdentity则直接代表着一个Windows的用户账户。用此类我们可以获取相关用户信息。
同时System.Security.Principal.IdentityReference代表一个标识,其派生类NTAccount和SecurityIdentifier类可以分别代表账户全称和安全标识符 (SID)。不同IdentityReference可以通过Translate方法进行类型转换。
//注意:using System.Security.Principal;
//获得当前Windows用户
WindowsIdentity curUser = WindowsIdentity.GetCurrent();
//用户SID
SecurityIdentifier sid = curUser.User;
//用户全称
NTAccount ntacc = (NTAccount)sid.Translate(typeof(NTAccount));
Console.WriteLine(sid.Value);
Console.WriteLine(ntacc.Value);
输出:
S-1-5-21-2376214308-3361272619-2153758801-1000
Mgen-PC\Mgen
3. 使用IPrincipal判断用户账户类型(支持用户账户控制(UAC)提示)
System.Security.Principal.IPrincipal接口代表定义用户对象的基本功能,其派生类WindowsPrincipal可以理解为代表Windows用户账户的权限或者用户类型。IPrincipal规定方法IsInRole(string role)来判断用户是否属于指定的类型/角色。WindowsPrincipal类不仅实现了IPrincipal要求的IsInRole方法(参数是字符串),还重载了基于WindowsBuiltInRole枚举的IsInRole方法。WindowsBuiltInRole(MSDN:)包含了常见的Windows用户账户类比如:管理员,超级用户,用户,来宾用户……
当然IPrincipal是建立在IIdentity之上的,即只有知道了用户标识,才可以知道用户的基本功能。IPrincipal的Identity属性就返回IIdentity对象。当然派生的WindowsPrincipal则返回WindowsIdentity,后者则是IIdentity的派生类。
另外在Windows Vista,Windows 7和之后的Windows系统引入了用户账户控制(UAC:User Account Control),即便用户是管理员账户,系统仿佛并不会将此用户运行的程序作为管理员权限而运行(Vista之前的系统是这样做的),任何可能影响系统安全的操作都会直接显示在屏幕上让用户判断是否可以继续,当用户同意执行后,该操作才可以以管理员方式进行。这样大大减少了某些恶意程序的幕后运行,因为很多恶意程序往往是费尽周折得到管理员权限运行后就可以为所欲为了。
下面这段代码可以判断利用WindowsPrincipal来判断用户是否具有管理员权限,运行后用户账户控制会提示是否给予程序管理员权限。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Security.Principal;
namespace Mgen.TTC
{
class Program
{
static void Main()
{
WindowsPrincipal winPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool admin = winPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
if (!admin)
{
if (!RunUAC(Process.GetCurrentProcess().MainModule.FileName))
{
Console.WriteLine("不是管理员");
return;
}
}
Console.WriteLine("是管理员");
}
static bool RunUAC(string fileName)
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.FileName = fileName;
try
{
Process.Start(processInfo);
return true;
}
catch (System.ComponentModel.Win32Exception)
{ }
return false;
}
}
}