Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 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 Reply

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#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...