您可以在启动时自行提升程序。只需在开头执行以下代码:
public static void runAsAdmin(string[] args)
{
ProcessStartInfo proc = new ProcessStartInfo();
if (args != null)
proc.Arguments = string.Concat(args);
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
proc.Verb = "runas";
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
{
try
{
Process.Start(proc);
}
catch
{
//No Admin rights, continue without them
return;
}
//Close current process for switching to elevated one
Environment.Exit(0);
}
return;
}
此外,在获得管理员权限后,您可以禁用 UAC 通知(如果已启用)以在未来静默启动:
private void disableUAC()
{
RegistryKey regKey = null;
try
{
regKey = Registry.LocalMachine.OpenSubKey(ControlServiceResources.UAC_REG_KEY, true);
}
catch (Exception e)
{
//Error accessing registry
}
try
{
regKey.SetValue("ConsentPromptBehaviorAdmin", 0);
}
catch (Exception e)
{
//Error during Promt disabling
}
}