class="csharpcode">demo1:
/// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="append">是否是追加</param> private void ShowOutput(string str,bool append) { if (this.txtOutput.InvokeRequired) { this.txtOutput.Invoke(new MethodInvoker(() => { if (append) { this.txtOutput.AppendText(str); this.txtOutput.AppendText(System.Environment.NewLine); } else { this.txtOutput.Clear(); } })); } else { if (append) { this.txtOutput.AppendText(str); this.txtOutput.AppendText(System.Environment.NewLine); } else { this.txtOutput.Clear(); } } } private void btnRun_Click(object sender, EventArgs e) { Thread thread = new Thread(() => { ShowOutput("",false); //this.txtOutput.Clear(); ProcessStartInfo psi = new ProcessStartInfo("Ping.exe");//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到 //如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe psi.Arguments = this.txtMachine.Text;//设置命令参数 psi.CreateNoWindow = true;//不显示dos命令行窗口 psi.RedirectStandardOutput = true;// psi.RedirectStandardInput = true;// psi.UseShellExecute = false;//是否指定操作系统外壳进程启动程序 Process p = Process.Start(psi); StreamReader reader = p.StandardOutput;//截取输出流 string line = reader.ReadLine();//每次读取一行 while (!reader.EndOfStream) { ; ShowOutput(line,true); line = reader.ReadLine(); } p.WaitForExit();//等待程序执行完退出进程 p.Close();//关闭进程 reader.Close();//关闭流 }); thread.IsBackground = true; thread.Start(); } private void Form1_Load(object sender, EventArgs e) { this.txtMachine.Text = "127.0.0.1"; }
demo2:
/// <summary> /// appoint exe /// </summary> /// <param name="exeStr"></param> /// <param name="fileStr"></param> public void OpenFile(string exeStr,string fileStr) { //ProcessStartInfo ProcessStartInfo psi; if (String.IsNullOrEmpty(exeStr)) { psi = new ProcessStartInfo(); } else { psi = new ProcessStartInfo(exeStr);//应用程序或文档名 } psi.Arguments = fileStr; Process process = new Process(); process.StartInfo = psi; process.Start(); } public void OpenFile(string fileStr) { OpenFile(null, fileStr); }