Programatically Add Exceptions to a Windows Firewall Using C#

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Programatically Add Exceptions to the Windows Firewall Using C#

I think many of us have had, at some point, problems configuring SQL Server 2005 and received the following error message:

"Microsoft SQL Native Client: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections."

To fix this problem, you need to enable a remote connection, turn on the SQL Server Browser Service, SQL Server, and SQL server Browser services to Firewall Exceptions. If you want more information about the first two matters, see http://support.microsoft.com/kb/914277.

My problem started when I had to add exceptions to a Windows Firewall programmatically. I really didn't like to modify Registry keys, but at that moment and circumstances, it was the only solution.

It is an observation to make at this point: You need to add exceptions for standard and domain profiles.

First of all, you need to include:

using Microsoft.Win32;
using System.Collections;

Declare variables:

private const string keyToSearchStandardProfile =
   @"SYSTEM\CurrentControlSet\Services\Share";
private const string keyToSearchDomainProfile =
   @"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FireWall";

//location to this exe files
private const  string applicationGeneralPath =
   @"C:\Program Files\Microsoft SQL Server";
private const string sqlbrowserPath = @"\90\Shared\sqlbrowser.exe";
private const string sqlservPath = @"\MSSQL.1\MSSQL\Binn\sqlservr.exe";

In both cases, I look whether these files are already added to the Windows Firewall exceptions and, only if they aren't, I add them.

  1. Add to standard profile:
  2. private void AddExceptionsToStandardDomain()
    {
       string keyValue;
    
       //add to standard profile if does not exist
       RegistryKey key =
       Registry.LocalMachine.OpenSubKey
          (keyToSearchStandardProfile, true);
    
       // add sqlservr
       keyValue = applicationGeneralPath +
          @"\MSSQL.1\MSSQL\Binn\sqlservr.exe:*:Enabled:sqlservr";
    
       //check if key exists
       bool appAlreadyExist =
          new ArrayList(key.GetValueNames()).Contains(keyValue);
       if (!appAlreadyExist)
          key.SetValue(applicationGeneralPath + sqlservPath,
                       keyValue);
    
       //add sqlbrowser
       keyValue = applicationGeneralPath +
          @"\90\Shared\sqlbrowser.exe:*:Enabled:sqlbrowser";
       appAlreadyExist =
          new ArrayList(key.GetValueNames()).Contains(keyValue);
       if (!appAlreadyExist)
          key.SetValue(applicationGeneralPath + sqlbrowserPath,
                       keyValue);
       key.Close();
    
    }
    
  3. Add to domain profile:
  4. public static void AddExceptionsToDomainProfile()
    {
    
       string keyValue;
    
       //add to domain profile
       RegistryKey key =
          Registry.LocalMachine.OpenSubKey
             (keyToSearchDomainProfile, true);
    
       //sqlservr
       keyValue = applicationGeneralPath +
          @"\MSSQL.1\MSSQL\Binn\sqlservr.exe:*:Enabled:sqlservr";
       bool appAlreadyExist =
          new ArrayList(key.GetValueNames()).Contains(keyValue);
       if (!appAlreadyExist)
          key.SetValue(applicationGeneralPath+sqlservPath,
                       keyValue);
    
       //sqlbrowser
       keyValue = applicationGeneralPath +
          @"\90\Shared\sqlbrowser.exe:*:Enabled:sqlbrowser";
       appAlreadyExist =
          new ArrayList(key.GetValueNames()).Contains(keyValue);
       if (!appAlreadyExist)
          key.SetValue(applicationGeneralPath+sqlbrowserPath,
                       keyValue);
       key.Close();
    
    }
    

I hope this article is helpful to you. If you have any questions or suggestions, please do not hesitate to contact me.



About the Author

Daniela Ilea

.Net developer (MCP since september 2006) , passionate about mobile technologies. Lives in Timisoara, Romania

Comments

  • How to Add Exceptions in Vista OS

    Posted by ShankarRaghavendira on 04/06/2009 04:53am

    Hi, thanks for ur help...i have tried ur coding..It works fine in Windows Xp and Higher Version..But when i tried in Vista OS..It generated an Error Like object reference not set an instance of an object.. something like this.. i need ur help regarding how to add exceptions and Port settings in Vista OS ... Thanks & Regards, Shankar.G

    Reply
  • Need Help

    Posted by ShankarRaghavendira on 03/11/2009 07:12am

    Hi, am developing application in Vb.net..when i tried ur coding.an error generated...Object reference not set to an instance of an Object... How can i solve this issue.... How can i add port and Exception Programs in a Windows Firewall by Code... Thanks & Regards, Shankar.G

    • Have a look at this

      Posted by cuonchagio on 11/18/2009 03:47am

      http://bytes.com/topic/c-sharp/answers/259855-adding-port-xp-firewall
      
      Hope this help!

      Reply
    • Help

      Posted by DanielaTm on 03/11/2009 08:57am

      Hello, Here is the thing: I developed this code on Win XP. In this moment, I have access only to Win 2003 server, but I can tell you what to do: 1. First of all, take each constant. Verify using regedit (Start-Run- regedit) if the paths are compatible. For example, for the constant keyToSearchStandardProfile in win 2003 server is not the same. 2. applicationGeneralPath is default to C: . You need to see if there is Microsoft sql server installed 3. This code adds in Windows firefall, so, if you use another firewall it might work if you set the correct path of the constants. Feel free to send a private message if you still have problems after that Regards, Daniela

      Reply
    Reply
  • Useful stuff

    Posted by Carolyn52 on 09/01/2007 01:48am

    Useful stuff.Thanks

    Reply
  • nice

    Posted by sandu_tm on 08/30/2007 01:36pm

    Nice!

    • Dear collegue

      Posted by DanielaTm on 08/31/2007 03:29am

      I made a class in c#. In the variable declaration dection, you need to fill the correct path of the variable applicationGeneralPath. You need to check if the location of the sql server is correct. Then, you just need to call the methods. If you still have problems using it, please email directly to me your questions and I will be happy to guide you step by step Daniela Ilea

      Reply
    • Thank You

      Posted by sushovan.mukherjee on 08/30/2007 05:39pm

      Thank you I am facing exactly this problem. But I couldn't understand what will I do. But I am a begineer in this section so I can't understand where shall I write this. Please help me. I am in very big problem.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date