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;
}
}
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.
Testabc user have the administrator right.
//Run EXTERNAL APP AS AN ADMIN
var pass = new SecureString();
pass.AppendChar('t');
pass.AppendChar('e');
pass.AppendChar('s');
pass.AppendChar('t');
var ps1File = @"C:\Users\testabc\Desktop\LT_Admin.ps1";
ProcessStartInfo processAdmin;
processAdmin = new ProcessStartInfo();
processAdmin.UseShellExecute = false;
processAdmin.CreateNoWindow = true;
processAdmin.WindowStyle=System.Diagnostics.ProcessWindowStyle.Hidden;
processAdmin.Password = pass;
processAdmin.UserName = "testabc";
processAdmin.Domain = "soft";
processAdmin.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
processAdmin.Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\"";
processAdmin.RedirectStandardOutput = true;
Process.Start(processAdmin);
In ps1File I have this code
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -Verb RunAs
Working perfectly...
User contributions licensed under CC BY-SA 3.0