The INetFwPolicy2 interface allows an application or service to access the firewall policy.
I am using visual studio 2017.
Question is related to this https://stackoverflow.com/a/33700472/2451446
Code is little different and I have problem to disable fire wall.
Logic before disable fire wall is ok.
public Task<StatusCodeResult> ResetFirewallStatus()
{
Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
dynamic mgr = Activator.CreateInstance(netFwPolicy2Type);
var fwCurrentProfileTypes = mgr.CurrentProfileTypes;
// Get current status
bool firewallEnabled = mgr.FirewallEnabled(fwCurrentProfileTypes); // return true
// Disables Firewall
mgr.FirewallEnabled(false); //breaks here !!!!
return Task.FromResult<StatusCodeResult>(Ok());
}
error message is:
System.ArgumentException: 'Value does not fall within the expected range.'
I tried to use set_FirewallEnabled(fwCurrentProfileTypes,false);
and also put_FirewallEnabled(fwCurrentProfileTypes,false)
In this case error is:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'set_FirewallEnabled'' ('put_FirewallEnabled'')
Edit
MY SOLUTION:
const int domainProfile = 1;
const int privateProfile = 2;
const int publicProfile = 4;
public bool EnableDisableFirewall(bool enableFirewall)
{
dynamic mgr = getFwPolicy2();
mgr.FirewallEnabled[domainProfile] = enableFirewall;
mgr.FirewallEnabled[privateProfile] = enableFirewall;
mgr.FirewallEnabled[publicProfile] = enableFirewall;
return enableFirewall;
}
public bool IsFirewallOn()
{
dynamic mgr = getFwPolicy2();
// Get current status
var isDomainProfileEnabled = mgr.FirewallEnabled(domainProfile);
var isPrivateProfileEnabled = mgr.FirewallEnabled(privateProfile);
var isPublicProfileEnabled = mgr.FirewallEnabled(publicProfile);
return isDomainProfileEnabled && isPrivateProfileEnabled && isPublicProfileEnabled;
}
private object getFwPolicy2()
{
Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
dynamic mgr = Activator.CreateInstance(netFwPolicy2Type);
return mgr;
}