2014年5月8日 星期四

利用 cmd 執行 program

 public string RunProgram(string prog, string param)
{
            string cmdoutput = "";
            //實例一個Process類,啟動一個獨立進程  
            Process p = new Process(); //Process類有一個StartInfo屬性,這個是ProcessStartInfo類,  
            //包括了一些屬性和方法,下面我們用到了他的幾個屬性:  
            p.StartInfo.FileName = prog; //設定程序名  
            p.StartInfo.Arguments = param; //設定程式執行參數  
            p.StartInfo.UseShellExecute = false; //關閉Shell的使用
            p.StartInfo.RedirectStandardInput = true; //重定向標準輸入
            p.StartInfo.RedirectStandardOutput = true; //重定向標準輸出  
            p.StartInfo.RedirectStandardError = true; //重定向錯誤輸出  
            p.StartInfo.CreateNoWindow = true; //設置不顯示窗口  
            p.Start(); //啟動 
            cmdoutput = p.StandardOutput.ReadToEnd(); //從輸出流取得命令執行結果                     
            return cmdoutput;
 }
////////////////////////////////////////////////////////////////////
string cmd = "";
            string devID = "USB\\VID_" + m_VID2 + "&PID_" + m_PID2;
            //cmd = "DeviceID.bat";
            cmd = RunProgram("devcon.exe", "remove BTH\\MS_BTHBRB");
            cmd += "\n";
            cmd += RunProgram("devcon.exe", "remove BTH\\MS_BTHPAN");
            cmd += "\n";
            cmd += RunProgram("devcon.exe", "remove BTH\\MS_RFCOMM");
            cmd += "\n";
            cmd += RunProgram("devcon.exe", "remove " + devID);

-----------------------------------------------
[範例2]
public string RunCommand(string sCommand,string sArg, int iSecTimeOut)
{
//实例一个Process类,启动一个独立进程
Process p = new Process();

//Process类有一个StartInfo属性,这个是ProcessStartInfo类,包括了一些属性和方法,下面我们用到了他的几个属性:
p.StartInfo.FileName = sCommand; //设定程序名
p.StartInfo.Arguments = sArg; //设定程序执行参数
p.StartInfo.UseShellExecute = false; //关闭Shell的使用
p.StartInfo.RedirectStandardInput = true; //复位向标准输入
p.StartInfo.RedirectStandardOutput = true; //复位向标准输出
p.StartInfo.RedirectStandardError = true; //复位向错误输出
p.StartInfo.CreateNoWindow = true; //设置不显示窗口

p.Start(); //启动
p.WaitForExit(iSecTimeOut*1000);//等待上述进程执行完毕
//如果是超过WaitForExit等待时间,则进程并未关闭,可能出现错误,需要手动将其关闭。
if (p.HasExited == false)
{
p.Kill();
return "外部调用响应超时";
}
//return p.StandardOutput.ReadToEnd(); //从输出流取得命令执行结果
return string.Empty;
}
                 

沒有留言:

[c#] process 使用方法

寫法1. Process proc = new Process(); / /PowerShell.exe path proc.StartInfo.FileName = @"c:\Windows\System32\ WindowsPowerShell\v1.0\ powe...