日期:2014-05-18  浏览次数:21126 次

C#如何与命令行工具交互
OpenSSL 是一个命令行工具,我要给它做一个GUI程序,使用如下代码调用命令行工具:

Process p = ...;
p.StartInfo.UseShellExecute = false;  
p.StartInfo.RedirectStandardInput = true;  
p.StartInfo.RedirectStandardOutput = true;  
p.StartInfo.RedirectStandardError = true;  
p.StartInfo.CreateNoWindow = true;  
p.Start();
p.RedirectStandardError.ReadToEnd();
p.WaitForExit();
p.Close();  

这段代码可以执行简单的命令,但是有些命令需要与 OpenSSL 进行交互。在命令提示符窗口使用 OpenSSL 的某些命令时,它会提示输入姓名,Email 之类的东西,手工输出这些信息后程序才能继续执行。

请问如何用C#代码实现类似功能。谢谢。


------解决方案--------------------
我记得可以通过设置p.StartInfo的参数来交互。具体操作忘记了,你可以查查!
------解决方案--------------------
《C#中运行命令行截取输出流的例子(流重定向)》: 
说明:经常有朋友问如何在C#中运行一个dos命令,并截取输出、输出流的问题,这个问题我以前在Java中实现过,由于在C#中没有遇到过类似的 情况,为了避免每次别人问都要一遍一遍演示的情况,特地做了一个简单的例子,实现在WinForm中ping一个网站,并且将ping的结果显示在一个文本框中。 
http://blog.csdn.net/zhoufoxcn/archive/2007/07/07/1682130.aspx 

看看这个吧。
------解决方案--------------------
C# code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace RunCMD
{
    /**
     * 作者:周公
     * blog:http://blog.csdn.net/zhoufoxcn
     * 日期:2007-07-07
     * 
     * */
    public partial class CMDForm : Form
    {
        public CMDForm()
        {
            InitializeComponent();
        }

        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();//关闭流
        }
    }
}

------解决方案--------------------
C# code

SreamWriter writer = p.StandardInput();
writer.WriterLine("name");
writer.WriterLine("email");

------解决方案--------------------
:)
------解决方案--------------------
up
------解决方案--------------------
支持<周公>
------解决方案--------------------
学习了!!
帮你顶!!