网上有很多用C#调用cmd的方法,大致如下:
上面代码有几个不足,一是必须要exit那一句,否则就会死循环。再就是每次执行Execute执行cmd后,都必须等到cmd执行完且
cmd.exe进程退出,才能读到结果。有时候这样会让我们的应用程序失去操作的连续性。
事实上,通过两个线程,一个访问输入管道,一个访问输出管道,可以很容易实现持续性的效果,下面是一个Console程序:
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);
}
}
}
}
本文介绍了一种使用C#调用CMD的方法,通过创建两个独立线程分别处理输入和输出,实现了应用程序与CMD之间的持续交互,提高了操作的连贯性和效率。
1万+

被折叠的 条评论
为什么被折叠?



