加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – cmd.exe shell的输入和输出

发布时间:2020-12-15 21:19:02 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个与命令提示符 shell(cmd.exe)交互的 Windows窗体C#项目. 我想打开一个命令提示符,发送一个命令(如ipconfig),然后将结果读回到windows窗体中,形成一个字符串,文本框或其他内容. 这是我到目前为止所做的,但我被卡住了.我无法写入或读取命令
我正在尝试创建一个与命令提示符 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();

        }
    }
}

任何帮助将不胜感激.

谢谢.

解决方法

这是一个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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读