I just made this work in vb.NET.
Add a refrence to "c:\windows\system32\firewallapi.dll"
Make a class called Firewall - like so:
Imports NetFwTypeLib
Imports System.Net
Public Class Firewall
Implements IDisposable
Private _policy As INetFwPolicy2 = Nothing
Private ReadOnly Property Policy As INetFwPolicy2
Get
If _policy Is Nothing Then
_policy = DirectCast(Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")), INetFwPolicy2)
End If
Return _policy
End Get
End Property
Public Sub Add(ipAddress As IPAddress, ruleName As String)
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
If Not firewallRule.RemoteAddresses.Contains(NewAddress) Then
firewallRule.RemoteAddresses += "," & NewAddress
End If
End Sub
Public Sub Remove(ipAddress As IPAddress, ruleName As String)
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
If firewallRule.RemoteAddresses.Contains(NewAddress) Then
Dim ipList As String = firewallRule.RemoteAddresses
ipList = ipList.Replace(NewAddress, "")
ipList = ipList.Replace(",,", ",")
firewallRule.RemoteAddresses = ipList
End If
End Sub
Public Function Exists(ipAddress As IPAddress, ruleName As String) As Boolean
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
If firewallRule.RemoteAddresses.Contains(NewAddress) Then
Return True
Else
Return False
End If
End Function
Private disposedValue As Boolean
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
End If
If Not _policy Is Nothing Then
_policy = Nothing
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class