最近在設計網站後台管理系統的時候,想到了是否可以通過頁面重啟Windows服務器
到Google搜索了一下,找到了一段似乎很普遍的代碼
事實證明,這段代碼在寫桌面應用例如Console或者Windows Form程序的時候可以正常運行,但是通過ASP.NET調用則無法通過
但是我還是把這段代碼貼出來,因為其中除了個別兩行外,其他的還是重啟服務器的必須代碼
新建一個類,在裡面填入如下代碼:
首先是命名空間,調用Win API的時候,InteropServices不可少:
using System;
using System.Runtime.InteropServices;
然後是一系列的常量聲明:
protected const int SE_PRIVILEGE_ENABLED = 0x2;
protected const int TOKEN_QUERY = 0x8;
protected const int TOKEN_ADJUST_PRIVILEGES = 0x20;
protected const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
protected const int EWX_LOGOFF = 0x0;
protected const int EWX_SHUTDOWN = 0x1;
protected const int EWX_REBOOT = 0x2;
protected const int EWX_FORCE = 0x4;
protected const int EWX_POWEROFF = 0x8;
protected const int EWX_FORCEIFHUNG = 0x10;
定義Luid結構,注意屬性:
[StructLayout(LayoutKind.Sequential, Pack=1)]
外部非托管DLL的聲明:
protected struct LuidStruct {
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling=true)]
protected static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError=true)]
protected static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError=true)]
protected static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport("advapi32.dll", SetLastError=true, ExactSpelling=true)]
protected static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref LuidStruct newst, int len, IntPtr prev, IntPtr relen);
[DllImport("user32.dll", SetLastError=true, ExactSpelling=true)]
protected static extern bool ExitWindowsEx(int flg, int rea);