微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试创建一个与命令提示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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐