I am working on a project where it must be possible to enable/disable the integrated Windows Firewall of a Windows 7 Embedded system by programm.
using the code:
private static INetFwPolicy2 getCurrPolicy()
{
INetFwPolicy2 fwPolicy2;
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
if (tNetFwPolicy2 != null)
fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
else
return null;
return fwPolicy2;
}
public static bool GetFirewallStatus()
{
bool result = false;
try
{
INetFwPolicy2 fwPolicy2 = getCurrPolicy();
NET_FW_PROFILE_TYPE2_ fwCurrentProfileTypes;
//read Current Profile Types (only to increase Performace)
//avoids access on CurrentProfileTypes from each Property
fwCurrentProfileTypes = NET_FW_PROFILE_TYPE2_)fwPolicy2.CurrentProfileTypes;
result = (fwPolicy2.get_FirewallEnabled(fwCurrentProfileTypes));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return result;
}
public static void SetFirewallStatus(bool newStatus)
{
try
{
NET_FW_PROFILE_TYPE2_ fwCurrentProfileTypes;
INetFwPolicy2 currPolicy = getCurrPolicy();
//read Current Profile Types (only to increase Performace)
//avoids access on CurrentProfileTypes from each Property
fwCurrentProfileTypes = NET_FW_PROFILE_TYPE2_)currPolicy.CurrentProfileTypes;
currPolicy.set_FirewallEnabled(fwCurrentProfileTypes, newStatus);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
What happens is that at every function call of the currPolicy objects i get the following message:
System.ArgumentException: Value does not fall within the expected range.
Now there is my question: Why do I get this error and how can I make it work?
Thanks!
After reading the documentation again, i came across the line "When you pass a profile type obtained from the CurrentProfileTypes property, make sure that you pass only one profile type to get_FirewallEnabled and put_FirewallEnabled. Note that get_CurrentProfileTypes can return multiple profiles."
(http://msdn.microsoft.com/en-us/library/windows/desktop/aa365316%28v=vs.85%29.aspx)
And yes, i have actually got more than one profile type returned. So the API works when you only pass one profile to the get and set methods of FirewallEnabled. e.g.:
result = (fwPolicy2.get_FirewallEnabled(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC));