I am a new guy in C# development and I am looking for a App to define a firewall rule...
I searched nearly everywhere and found some code using NetFwMgr
but it didn't work and I don't know why!?
but I knew the cmd
code for it, so I started to use the Process
way in visual studio 2019
.
the code line in cmd
works fine and returns the word "OK." but I cant do it in C#
if anyone can help me understand the concept of it, I would be appreciate it.
here is the code snippet of what I have done:
try
{
string str = "netsh advfirewall firewall add rule name="+"\"Port for SQL\""+" dir=in action=allow
protocol=TCP localport=1433";
ProcessStartInfo psi = new ProcessStartInfo();
Process process = new Process();
psi.FileName = "cmd.exe";
psi.WindowStyle = ProcessWindowStyle.Normal;
psi.Verb = "runas";
psi.Arguments = str;
process.StartInfo = psi;
process.Start();
process.WaitForExit(1000);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
the thing it does nothing. it simply waits for 1 second and nothing happens. it doesn't even catches any errors. Please Help
UPDATE : I even ran the exe file as administrator and nothing happens... I also gave the application manifest admin access:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
still no good
You are calling cmd.exe
and not netsh
. The string you are passing as argument is not extecuted in the newly created console, you'd need to run cmd /c ...
for that.
Just use netsh
as your psi.Filename
and advfirewall ...
as your argument
string str = "advfirewall firewall add rule name=" + "\"Port for SQL\"" + " dir=in action=allow protocol=TCP localport=63000";
ProcessStartInfo psi = new ProcessStartInfo();
Process process = new Process();
psi.FileName = "netsh";
psi.WindowStyle = ProcessWindowStyle.Normal;
psi.Arguments = str;
process.StartInfo = psi;
process.Start();
process.WaitForExit();