使用VB.Net在Windows防火墙中创建例外

时间:2013-01-24 06:27:00

标签: vb.net visual-studio windows-firewall

如何使用vb.net代码将我的应用程序添加到Windows防火墙的例外列表中?

由于

1 个答案:

答案 0 :(得分:0)

Windows Vista和7提供了相当强大的防火墙API,可用于向防火墙添加例外。如果代码以管理员权限运行,下面的代码将为指定应用程序的Windows防火墙添加一个例外。在您的应用程序中添加对%systemroot%\ system32 \ FirewallAPI.dll 的引用。

Imports NetFwTypeLib

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    ' Create the Application we want to add to the exception list
    Dim appType As Type = Type.GetTypeFromProgID("HnetCfg.FwAuthorizedApplication")
    Dim app As INetFwAuthorizedApplication
    app = DirectCast(Activator.CreateInstance(appType), INetFwAuthorizedApplication)

    ' Set the application properties
    app.Name = "Negative0's Sandbox"
    app.ProcessImageFileName = "C:\Users\Negative0\vbsandbox2.exe"
    app.Enabled = True


    ' Get the firewall manager, so we can get the list of authorized apps
    Dim fwMgrType As Type = Type.GetTypeFromProgID("HnetCfg.FwMgr")
    Dim fwMgr As INetFwMgr
    fwMgr = DirectCast(Activator.CreateInstance(fwMgrType), INetFwMgr)

    ' Get the list of authorized applications from the Firewall Manager, so we can add our app to that list
    Dim apps As INetFwAuthorizedApplications
    apps = fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications
    apps.Add(app)

End Sub

Source