【问题标题】:Input & Output from cmd.exe shellcmd.exe shell 的输入和输出
【发布时间】:2011-09-04 03:55:45
【问题描述】:

我正在尝试创建一个与命令提示符 shell (cmd.exe) 交互的 Windows 窗体 C# 项目。

我想打开一个命令提示符,发送一个命令(如 ipconfig),然后将结果读回 windows 窗体中的字符串、文本框或其他任何内容。

这是我目前所拥有的,但我被卡住了。我无法写入或读取命令提示符。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;


namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/k dir *.*";
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.Start();

            StreamWriter inputWriter = p.StandardInput;
            StreamReader outputWriter = p.StandardOutput;
            StreamReader errorReader = p.StandardError;
            p.WaitForExit();

        }
    }
}

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 为什么要运行cmd.exe?假设 ipconfig 是一个独立的可执行文件,你应该可以直接运行它。
  • ipconfig 可能只是概念的一个例子/教授。

标签: c# windows winforms command-line


【解决方案1】:
  var yourcommand = "<put your command here>";

  var procStart = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + yourcommand);
  procStart.CreateNoWindow = true;
  procStart.RedirectStandardOutput = true;
   procStart.UseShellExecute = false;

   var proc = new System.Diagnostics.Process();
   proc.StartInfo = procStart;
   proc.Start();
   var result = proc.StandardOutput.ReadToEnd();

   Console.WriteLine(result);

【讨论】:

    【解决方案2】:

    这是一个 SO 问题,可为您提供所需的信息:

    How To: Execute command line in C#, get STD OUT results

    基本上,您的 System.IO.StreamReader 上的 ReadToEnd。

    因此,例如,在您的代码中,您可以将StreamReader errorReader = p.StandardError; 行修改为阅读

    using(StreamReader errorReader = p.StandardError)
    {
       error = myError.ReadToEnd();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2023-03-20
      相关资源
      最近更新 更多