C#中运行一个dos命令,并截取输出、输出流

转:http://topic.csdn.net/u/20081218/16/7fd5c8dc-fbdc-41a9-a57b-cca8504c0731.html

 

一、

string arg = string.Format(backupFmt, server, user, pwd, database, file);
  Process p = new Process();
  p.StartInfo.FileName = "cmd.exe";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.WorkingDirectory = location + @"bin";
  p.StartInfo.Arguments = arg;
  p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardInput = true;
  p.StartInfo.RedirectStandardOutput = true; p.Start();

  StreamWriter sw = p.StandardInput;
  sw.WriteLine(arg);
  sw.WriteLine(Environment.NewLine);
  sw.Close();
#if DEBUG
  StreamReader sr = p.StandardOutput;
string str = sr.ReadToEnd();
if(!string.IsNullOrEmpty(str))
{
Console.WriteLine("restore file:" + file);
Console.WriteLine("message:" + str);
}
sr.Close();
#endif
  p.WaitForExit();
  p.Close();

 

二、

说明:经常有朋友问如何在C#中运行一个dos命令,并截取输出、输出流的问题,这个问题我以前在Java中实现过,由于在C#中没有遇到过类似的 情况,为了避免每次别人问都要一遍一遍演示的情况,特地做了一个简单的例子,实现在WinForm中ping一个网站,并且将ping的结果显示在一个文 本框中。

 

 

private void btnExecute_Click(object sender, EventArgs e)
{
    tbResult.Text = "";
    ProcessStartInfo start = new ProcessStartInfo("Ping.exe");
    //设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到
    //如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe
    start.Arguments = txtCommand.Text;//设置命令参数
    start.CreateNoWindow = true;//不显示dos命令行窗口
    start.RedirectStandardOutput = true;//
    start.RedirectStandardInput = true;//
    start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
    Process p=Process.Start(start);
    StreamReader reader = p.StandardOutput;//截取输出流
    string line = reader.ReadLine();//每次读取一行
    while (!reader.EndOfStream)
    {
        tbResult.AppendText(line+" ");
        line = reader.ReadLine();
    }
    p.WaitForExit();//等待程序执行完退出进程
    p.Close();//关闭进程
    reader.Close();//关闭流
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值