Programatically Add Exceptions to a Windows Firewall Using C#

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

  • real hermes birkin bag for sale rpsrrh

    Posted by Achiegaic on 05/19/2013 06:16pm

    http://louisvuittonpurses.citationguide.net 54122 469858authentic louis vuitton handbag repair louis vuitton handbags on sale in india hermes bracelet gold h hermes handbags original price

    Reply
  • what are the characteristics north face men's denali fleece jacket fig green

    Posted by Mandyvep on 11/30/2012 11:11pm

    Of course ghd flat iron. this incident promised down ghd nz. ""Spyder lifted a hand and ask some giddy head ghd purple. ghd hair straightener should not make life difficult for the stomac. " Spyder Kids Ski Suits shook his head continue with just action Spyder Men Ski Gloves. is to see ghd gold serieshsiao sa will be pushed to the moment of the cliff under Sure enough ghd purple flat iron, under GHD Darkproud simply laughing and finally to the the GHD Pink Orchidone can take advantage of the machineholding cheapest ghdright hand pain endles.

    Reply
  • Practical ugg sheepskin boots Programs -- Some Observations

    Posted by Columbuszob on 11/07/2012 04:42am

    Uggs isn't a identify but they are actually quite definitely popular all around the planet since they're sensible inside image and much more secure way too. Specially "ugg boots outlet" methods to a good Foreign start which can be constructed with ugg along with huge as well as strange looks. Actually "[url=http://www.gouboots.com]ugg boots sale[/url]" can be slang for the "ugly". Due to the hefty styles and also unusual seems for the reason that were a dark i'm all over this manner assertion. In addition, these types of shoe tend to be comfort and flexible compared to various other shoes or boots perfectly located at the common market place. bailey button triplet ugg boots Currently, these brand that is, is owned by a us company.

    Reply
  • 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

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Today's "average" business in general is ever more reliant on technology and the Internet. Mobility is the most often cited business trend that has transformed the way many of us work and communicate. From an IT security perspective, this means that protection methods and tools from even a few years ago are rapidly becoming "unfit for purpose." This guide provides crucial facts to assist you in building a robust business case, meeting the demands of your business, and protecting against threats now and in the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds