简体   繁体   中英

A specified value is not valid. Adding firewall rule with C#

I made a little Windows Form Application to create firewall rules by just Drag and droping .exe files and it doesn't work if the .exe file is in

X:\\Program Files (x86)... or in X:\\Program files...

part of my code where i think the problem is:

    private void button1_Click(object sender, EventArgs e)
    {

        foreach (string item in listBox1.Items)
        //MessageBox.Show(Path.GetFileName(item));

        {
            string addToFirewall = "/K netsh advfirewall firewall add rule name=" + Path.GetFileName(item) + " dir=out action=block program=" + item;
            System.Diagnostics.Process proc2 = new System.Diagnostics.Process();
            proc2.StartInfo.CreateNoWindow = false;
            proc2.StartInfo.Verb = "runas";
            proc2.StartInfo.FileName = "cmd";
            proc2.StartInfo.Arguments = "/env /user:" + "Administrator" + "cmd" + addToFirewall;
            proc2.Start();
            //MessageBox.Show(addToFirewall);
        }

    } 

For example, a valid CMD command to add/create a firewall rule would be:

netsh advfirewall firewall add rule name="GOM.EXE" dir=out action=block program="C:\Program Files (x86)\GRETECH\GomPlayer\GOM.EXE"

and if i drag and drop GOM.exe file and try to create firewall rule i get an error:

A specific value is not valid. 图片

My first guess is that something is wrong with blank spaces between

Program( )Files and Program( )Files( )(x86)

Your problem is that Program Files contains a space, so you need to add quotes around it. Change your line to this:

string addToFirewall = "/K netsh advfirewall firewall add rule name=" + Path.GetFileName(item) + " dir=out action=block program=\"" + item + "\"";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM