使用C#打开和关闭防火墙

时间:2016-07-18 12:09:21

标签: c# .net windows-firewall-api

我编写了一个使用命令行参数的C#程序 打开和关闭防火墙。

Process proc = new Process();
string top = "netsh.exe";
proc.StartInfo.Arguments = "**Advfirewall set allprofiles state on**";
proc.StartInfo.FileName = top;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
// MessageBox.Show("Disable");
button1.Text = "Set On";
status = false;

我还使用管理员权限运行该应用程序。应用程序自动以管理员权限运行,但不会打开或关闭防火墙状态。

当我在cmd(netsh)中运行相同的命令时,防火墙会打开或关闭。

有谁知道为什么这不起作用?

1 个答案:

答案 0 :(得分:2)

运行相同的代码但删除class ImportTSV_Model extends CI_Model { private $strFile = "data.tsv"; private $masterNodeId = "41"; private $arrDataObjects = array(); public function __construct() { $this->prepareDataFromFile(); } public function import() { $objMasterNode = $this->arrDataObjects[$this->masterNodeId]; $this->save($objMasterNode); } private function save($objNode) { $arrInsertToDbData = array( "sandi" => $objNode->sandi, "pendapatan" => $objNode->pendapatan, "parent_id" => $objNode->mysqlParentId ); $this->db->insert("your_table", $arrInsertToDbData); $id = $this->db->insert_id(); if (count($objNode->arrChilds) > 0) { foreach($objNode->arrChilds AS $objNode) { $objNode->mysqlParentId = $id; $this->save($objNode); } } } private function prepareDataFromFile() { $file = FCPATH."assets/".$this->strFile; $objFile = new SplFileObject($file); while(!$objFile->eof()) { $line = $objFile->fgets(); $arrDataPerLine = explode("\t",$line); $objTSVData = new TSVData_Object; $objTSVData->prepareDataFromLine($arrDataPerLine); $this->arrDataObjects[$objTSVData->formattedSandi] = $objTSVData; } foreach($this->arrDataObjects AS $objItem) { //set parent ID $parent = substr($objItem->formattedSandi,0,-1); if (isset($this->arrDataObjects[$parent])) $this->arrDataObjects[$parent]->addChild($objItem); } } } class TSVData_Object { public $sandi; public $pendapatan; public $formattedSandi; public $mysqlParentId = 0; public $arrChildObjects = array(); public function prepareDataFromLine($arrLine) { $this->sandi = $arrLine[0]; $this->pendapatan = $arrLine[1]; $this->formattedSandi = str_replace(".","",$this->sandi); } public function addChild(TSVData_Object $objItem) { $this->arrChildObjects[] = $objItem; } } 似乎有效。即你需要改变这个:

**

到此:

proc.StartInfo.Arguments = "**Advfirewall set allprofiles state on**";

请注意,您应该运行以管理员身份启动流程的应用,并以管理员身份启动流程,您也可以使用:

proc.StartInfo.Arguments = "Advfirewall set allprofiles state on";