category: Dev
tags: [c#, firewall]
reference site :
crystalcube.co.kr/12

개요

cmd 프로세서를 이용해서 netsh 명령으로 간단하게 처리하는 방법.
xp부터 적용 가능한 것 같고, win7이후부터 작업이 추가된다.

소스

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
    /// <summary>
      ///  방화벽 예외 추가(xp~)
      /// </summary>
      /// <refer>http://crystalcube.co.kr/12</refer>
      public static class Fwall
      {
          private static readonly string FirewallCmd = "netsh firewall add allowedprogram \"{1}\" \"{0}\" ENABLE";
          private static readonly string AdvanceFirewallCmd = "netsh advfirewall firewall add rule name=\"{0}\" dir=in action=allow program=\"{1}\" enable=yes";
          private static readonly int VistaMajorVersion = 6;
          /// <summary>
          /// 방화벽 등록 
          /// </summary>
          /// <param name="name">등록할 product name </param>
          /// <param name="programFullPath">실행 경로</param>
          /// <returns>작업 성공 여부 </returns>
          public static bool AuthorizeProgram(string name, string programFullPath)
          {
              try
              { // OS version check
                  string strFormat = Fwall.FirewallCmd;
                  if (System.Environment.OSVersion.Version.Major >= Fwall.VistaMajorVersion)
                  {
                      strFormat = Fwall.AdvanceFirewallCmd;
                  }

                  // Start to register 
                  string command = String.Format(strFormat, name, programFullPath);
                  System.Console.WriteLine(command);

                  ProcessStartInfo startInfo = new ProcessStartInfo();
                  startInfo.CreateNoWindow = true;
                  startInfo.FileName = "cmd.exe";
                  startInfo.UseShellExecute = false;
                  startInfo.RedirectStandardInput = true;
                  startInfo.RedirectStandardOutput = true;
                  startInfo.RedirectStandardError = true;

                  Process process = new Process();
                  process.EnableRaisingEvents = false;
                  process.StartInfo = startInfo;
                  process.Start();
                  process.StandardInput.Write(command + Environment.NewLine);
                  process.StandardInput.Close();
                  string result = process.StandardOutput.ReadToEnd();
                  string error = process.StandardError.ReadToEnd();
                  process.WaitForExit();
                  process.Close();
              }
              catch
              {
                  return false;
              }
              return true;
          }
      }