C#判断程序是否以管理员身份运行,否则以管理员身份重新打开
/// summary
/// 判断程序是否是以管理员身份运行。
/// /summary
public static bool IsRunAsAdmin(){WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);}//不是以管理员身份开启,则自动以管理员身份重新打开程序
//写在构造里比较省资源
网页链接
public bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public void RunAdmin()
{
try
{
//判断是否以管理员身份运行,不是则提示
if (!IsAdministrator())
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = Environment.CurrentDirectory;
psi.FileName = Application.ExecutablePath;
psi.UseShellExecute = true;
psi.Verb = "runas";
Process p = new Process();
p.StartInfo = psi;
p.Start();
Process.GetCurrentProcess().Kill();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: "+ex.Message);
}
}
调用: RunAdmin();