Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c# - Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))' firewall INetFwPolicy2

Access is denied.

        private  void MakeRule(string IP, int Protocole, NET_FW_RULE_DIRECTION_ ruleDirection, string ruleName)
        {
            Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
            var currentProfiles = fwPolicy2.CurrentProfileTypes;

            

            // Let's create a new rule
            INetFwRule2 Rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
            Rule.Enabled = true;
            

            NET_FW_RULE_DIRECTION_ direction = ruleDirection;
            Rule.Direction = direction; //Inbound
            Rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            Rule.Profiles = currentProfiles;

            Rule.Protocol = protNumber; // ANY/TCP/UDP

            try
            {
                Rule.RemoteAddresses = str;
            }
            catch (Exception)
            {
                MessageBox.Show("Can't add Rules. Maybe a Format failure?");
            }

            //Rule.LocalPorts = "81"; //Port 81

            //Name of rule
            Rule.Name = ruleName;
            
            // ...//
            //Rule.Profiles = (int)NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_TYPE_MAX;

            // Now add the rule
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            try
            {
                firewallPolicy.Rules.Add(Rule);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to make your app run as administrator, you can create a manifest file to make it work.

First, please right click your project and add a new item called Application Manifest File.

Second, please find requestedExecutionLevel tag and change into the following tag:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />  

Third, you will get a UAC prompt when they start the program. Choose Restart under different credentials.

Finally, you can run the program with the amdin power.

Also, you can read the following link to use c# code to run the app as admin.

Run as administrator C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...