如何通过ASP.NET页面重启服务器

2009-05-12 22:21:04来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

到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)]
protected struct LuidStruct {
    public int Count;
    public long Luid;
    public int Attr;
}
外部非托管DLL的声明: [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);
在NT级的操作系统上,需要先通知Windows系统即将关机,并且要获得关机的权限

以下就是关机、重启以及注销的实现: protected static void DoExitWindows(int flg) {
    LuidStruct tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;

    OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
    AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    ExitWindowsEx(flg, 0);
}

public static void Shutdown() {
    DoExitWindows(EWX_SHUTDOWN);
}

public static void Reboot() {
    DoExitWindows(EWX_REBOOT | EWX_FORCE);
}

public static void Logoff() {
    DoExitWindows(EWX_LOGOFF);
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:几十个ASP.NET性能优化的常用方法

下一篇:.net开发工具LINQ框架设计指南