有时候需要在程序中调用命令行程序进行一些操作,例如ping一台服务器,就需要调用现有的命令行程序,我用两种方法实现了。
第一种:使用C#本身调用一个进程的类方法,其代码如下
Process p = new Process();
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();
p.StandardInput.WriteLine("mmscomp.exe" + @" D:\MMS\45ADA882.hdr"); //生成彩信文件
p.StandardInput.WriteLine();
p.StandardInput.AutoFlush=true;
Thread.Sleep(3000);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.Close();
richTextBox1.AppendText("已经生成!" + strRst+"\n");
richTextBox1.ScrollToCaret();
第二种:在C#中调用WIN32 API函数,其例子代码如下:
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
public static extern int WinExec(string exeName, int operType);
WinExec(@"mmscomp.exe D:\MMS\45ADA882.hdr", 5);
以上两种方法都可以。