有一个变通的做法.
* 在程序中用管理员权限重新打开自己.
* 在main函数中判断传入的参数, 执行完需要权限的功能后, 直接return.
var psi = new ProcessStartInfo();
psi.FileName = Assembly.GetExecutingAssembly().Location;
psi.Arguments = "ClearEventLog " + menuItem.Text;
psi.Verb = "runas";
var process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit();
static void Main(string[] args)
{
if (args.Length > 0)
{
if (args[0].ToLower() == "ClearEventLog".ToLower())
{
MainForm.ClearEventLog(args[1]);
return;
}
}
......
}
或者:
static void StartMyselfAsAdmin()
{
var psi = new ProcessStartInfo();
psi.FileName = Assembly.GetExecutingAssembly().Location;
psi.Arguments = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).ToArray());
psi.Verb = "runas";
var process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit();
}
public static bool IsAdministrator()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
static void Main(string[] args)
{
if(!IsAdministrator())
StartMyselfAsAdmin();
}