您可以call the API directly
,而不是调用可执行文件
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool InitiateSystemShutdownEx(
string lpMachineName,
string lpMessage,
uint dwTimeout,
bool bForceAppsClosed,
bool bRebootAfterShutdown,
uint dwReason);
如果出现问题,异常应该会为您指明正确的方向。一方面,您必须拥有SeShutdownPrivilege,并且必须启用它。
考虑到权限后,完整的代码应如下所示。注意:这里假设使用System.Security.AccessControl.Privelege 类,其中was released in an MSDN magazine article,可下载as linked from the article。
Privilege.RunWithPrivilege(Privilege.Shutdown, true, (_) =>
{
if (!NativeMethods.InitiateSystemShutdownEx(null /* this computer */,
"My application really needs to restart",
30 /* seconds */, true /* force shutdown */,
true /* restart */, 0x4001 /* application: unplanned maintenance */))
{
throw new Win32Exception();
}
}, null);
这将执行与您通过调用 shutdown.exe 尝试执行的操作相同的功能,但最关键的是,如果存在任何阻止成功关闭的故障或安全限制,它将引发异常。