# windows添加程序防火墙规则

在windows下,命令创建防火墙规则,使程序能通过防火墙

命令

C#
public sealed class Command
{
    public static string Windows(string arg, string[] commands)
    {
        return Execute("cmd.exe", arg, commands);
    }

    public static string Execute(string fileName, string arg, string[] commands)
    {
        Process proc = new Process();
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.FileName = fileName;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.RedirectStandardInput = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.Arguments = arg;
        proc.StartInfo.Verb = "runas";
        proc.Start();

        if (commands.Length > 0)
        {
            for (int i = 0; i < commands.Length; i++)
            {
                proc.StandardInput.WriteLine(commands[i]);
            }
        }

        proc.StandardInput.AutoFlush = true;
        proc.StandardInput.WriteLine("exit");
        string output = proc.StandardOutput.ReadToEnd();
        proc.StandardError.ReadToEnd();
        proc.WaitForExit();
        proc.Close();
        proc.Dispose();

        return output;
    }
}

创建

C#
string content = @"@echo off
cd  ""%CD%""
for /f ""tokens=4,5 delims=. "" %%a in ('ver') do if %%a%%b geq 60 goto new

:old
cmd /c netsh firewall delete allowedprogram program=""%CD%\可执行程序.exe"" profile=ALL
cmd /c netsh firewall add allowedprogram program=""%CD%\可执行程序.exe"" name=""规则名"" ENABLE
cmd /c netsh firewall add allowedprogram program=""%CD%\可执行程序.exe"" name=""规则名"" ENABLE profile=ALL
goto end
:new
cmd /c netsh advfirewall firewall delete rule name=""规则名""
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=tcp enable=yes profile=public
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=udp enable=yes profile=public
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=tcp enable=yes profile=domain
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=udp enable=yes profile=domain
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=tcp enable=yes profile=private
cmd /c netsh advfirewall firewall add rule name=""规则名"" dir=in action=allow program=""%CD%\可执行程序.exe"" protocol=udp enable=yes profile=private
:end";

System.IO.File.WriteAllText("firewall.bat", content);
Command.Execute("firewall.bat", string.Empty, new string[0]);