时间:2019-03-18 标签:c#formsprogramaddhttpaddurlacl

c# forms program add http add urlacl

我有一个 C# Windows 表单程序,它 运行 是一个自托管 api。 我目前必须手动 运行 命令

http add urlacl url=http://*:8888/ user=Users listen=yes

在管理员命令提示符下。

我想在程序为运行时自动添加这个。 我找到了几个答案,它们只指向 HttpSetServiceConfiguration 函数 MS 文档,但不幸的是 没有示例代码行显示如何 运行 此命令作为 c#。

我也想以编程方式添加防火墙端口,这也需要手动 运行 即

netsh advfirewall firewall add rule name="my local server" dir=in action=allow protocol=TCP localport=8888

如果有人能指出正确的方向,我将不胜感激。

您可以 运行 外部程序作为管理员使用 System.Diagnostics.ProcessStartInfo 和 "runas" 动词。如果启用了用户访问控制 (UAC),则 Windows 可能会在程序询问用户是否应允许该操作时停止执行该程序。如果当前用户没有管理员权限,则他们必须在允许操作之前向管理员帐户提供帐户凭据,此时您尝试执行的程序将恢复。

以管理员身份启动进程的代码如下所示:

using System;
using System.IO;
using System.Diagnostics;

...

static void DoNetshStuff() {
    // get full path to netsh.exe command
    var netsh = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.System),
        "netsh.exe");

    // prepare to launch netsh.exe process
    var startInfo = new ProcessStartInfo(netsh);
    startInfo.Arguments = "http add urlacl url=http://*:8888/ user=Users listen=yes";
    startInfo.UseShellExecute = true;
    startInfo.Verb = "runas";

    try
    {
        var process = Process.Start(startInfo);
        process.WaitForExit();
    }
    catch(FileNotFoundException)
    {
        // netsh.exe was missing?
    }
    catch(Win32Exception)
    {
        // user may have aborted the action, or doesn't have access
    }
}