日期:2010-03-26 浏览次数:20546 次
到Google搜索了一下,找到了一段似乎很普遍的代码
事实证明,这段代码在写桌面应用例如Console或者Windows Form程序的时候可以正常运行,但是通过ASP.NET调用则无法通过
但是我还是把这段代码贴出来,因为其中除了个别两行外,其他的还是重启服务器的必须代码
新建一个类,在里面填入如下代码:
首先是命名空间,调用Win API的时候,InteropServices不可少:
以下为引用的内容:
using System; [DllImport("advapi32.dll", SetLastError=true)] [DllImport("advapi32.dll", SetLastError=true)] [DllImport("advapi32.dll", SetLastError=true, ExactSpelling=true)] [DllImport("user32.dll", SetLastError=true, ExactSpelling=true)] 以下就是关机、重启以及注销的实现: protected static void DoExitWindows(int flg) { OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); public static void Shutdown() { public static void Reboot() { public static void Logoff() { |
至此,重启代码结束,这段代码可以很好地工作在交互环境下,也就是在用户已经登录进Windows的情况下
但是ASP.NET是运行在非交互环境下的,查阅MSDN,在ExitWindowsEx函数定义下面发现这样一段话:
The ExitWindowsEx function returns as soon as it has initiated the shutdown process. The shutdown or logoff then proceeds asynchronously. The function is designed to stop all processes in the caller's logon session. Therefore, if you are not the interactive user, the function can succeed without actually shutting down the computer. If you are not the interactive user, use the InitiateSystemShutdown or InitiateSystemShutdownEx function.
于是得到启发,发现非交互下重启服务器不可以用ExitWindowsEx,需要将其替换成InitiateSystemShutdown:
[DllImport("advapi32.dll", SetLastError=true, ExactSpelling=false)]
protected static extern bool InitiateSys