C# 调用cmd.exe的方法
网上有很多用C#调用cmd的方法,大致如下:
[c-sharp] view plaincopy
- private void ExecuteCmd(string command)
- {
- Process p = new Process();
- p.StartInfo.FileName = "cmd.exe";
- p.StartInfo.UseShellExecute = false;
- p.StartInfo.RedirectStandardInput = true;
- p.StartInfo.RedirectStandardOutput = true;
- p.StartInfo.CreateNoWindow = true;
- p.Start();
- p.StandardInput.WriteLine(command);
- p.StandardInput.WriteLine("exit");
- p.WaitForExit();
- this.textBox1.Text=textBox1.Text+ p.StandardOutput.ReadToEnd();
- p.Close();
- }
上面代码有几个不足,一是必须要exit那一句,否则就会死循环。 再就是每次执行Execute执行cmd后,都必须等到cmd执行完且cmd.exe进程退出,才能读到结果。有时候这样会让我们的应用程序失去操作的连续性。
事实上,通过两个线程,一个访问输入管道,一个访问输出管道,可以很容易实现持续性的效果,
下面是一个Console程序:
[c-sharp] view plaincopy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Diagnostics;
- namespace cmdtest
- {
- class Program
- {
- public static string cmd_str;
- public static string cmd_outstr;
- public static Process p = new Process();
- static void Main(string[] args)
- {
- p.StartInfo.FileName = "cmd.exe";
- p.StartInfo.UseShellExecute = false;
- p.StartInfo.RedirectStandardInput = true;
- p.StartInfo.RedirectStandardOutput = true;
- p.StartInfo.RedirectStandardError = true;
- p.StartInfo.CreateNoWindow = true;
- p.Start();
- cmd_str = "";
- cmd_outstr = "";
- Thread t1 = new Thread(new ThreadStart(DoCmdThread));
- t1.Start();
- Thread t2 = new Thread(new ThreadStart(OutCmdThread));
- t2.Start();
- while(true)
- {
- cmd_str = Console.ReadLine();
- Thread.Sleep(10);
- if (cmd_str == "exit")
- break;
- }
- }
- public static void DoCmdThread()
- {
- while (true)
- {
- if (cmd_str == "exit")
- break;
- if (cmd_str != "")
- {
- p.StandardInput.WriteLine(cmd_str);
- //p.StandardInput.WriteLine("cd");
- cmd_str = "";
- }
- Thread.Sleep(1);
- }
- }
- public static void OutCmdThread()
- {
- while (true)
- {
- if (cmd_str == "exit")
- {
- p.StandardInput.WriteLine("exit");
- p.WaitForExit();
- p.Close();
- break;
- }
- cmd_outstr = p.StandardOutput.ReadLine();
- while(cmd_outstr != "")
- {
- Console.WriteLine(cmd_outstr);
- cmd_outstr = p.StandardOutput.ReadLine();
- }
- char[] ch = new char[256];
- int c = p.StandardOutput.Read(ch, 0, 256);
- if (c > 0)
- {
- Console.Write(ch,0,c);
- }
- Thread.Sleep(1);
- }
- }
- }
- }