将命令/参数发送到已打开的命令提示符

时间:2014-12-18 00:20:47

标签: c# windows command-line-arguments command-prompt

所以我知道我已经启动cmd.exe进程,并在它打开的那一刻输入ping google.com。这可以很容易地完成:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SendComandToCMD
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;

            Process process = Process.Start(processStartInfo);

            if (process != null)
            {            
                process.StandardInput.WriteLine("ping google.com");

                process.StandardInput.Close(); // line added to stop process from hanging on ReadToEnd()

                lblResult.Text = process.StandardOutput.ReadToEnd(); // return CMD.exe output to the Form label here
            }
        }
    }
}

繁荣,这很容易。

然而,下面的例子在理论上做了我想做的事情,但它崩溃了:

namespace SendComandToCMD
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process process = Process.GetProcessById(22180); // Grab a process which is already running by its ID

            if (process != null)
            {            
                process.StandardInput.WriteLine("ping google.com");

                process.StandardInput.Close(); // line added to stop process from hanging on ReadToEnd()

                lblResult.Text = process.StandardOutput.ReadToEnd(); // return CMD.exe output to the Form label here
            }
        }
    }
}

因此,抓住新创建的进程的实例就像第一个示例一样完美,但是通过ID获取当前正在运行的CMD.EXE进程的实例将导致崩溃:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

我知道通过检查任务管理器我有一个运行PID为22180的cmd.exe,但是异常发生在:

process.StandardInput.WriteLine("ping google.com");

我找到一种写CMD.EXE的方法非常重要,原因很多,有没有人知道如何让上面的解决方案2起作用?

0 个答案:

没有答案