c# - 在C#中发送cmd命令并读取结果

标签 c# process cmd command-line-arguments command-prompt

我想发送带参数的命令并从 cmd 读取它们的答案。因此,我编写了下面的代码,但它无法正常工作并锁定在屏幕上(myString 通常为 null - "")。我只想将命令发送到打开的命令提示符。哪里有问题?提前致谢。 (例如:如何获取 ping 请求的结果?)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace CallBatchFile
{
    class Program
    {
        [STAThread]
        static void Main()
        {            

            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c date";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();

            string myString = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }
    }
} 

最佳答案

cmd/c date 正在阻塞。你可以使用

p.StartInfo.Arguments = "/c date /T";

要停止等待输入的日期,或者输入cmd

p.StartInfo.RedirectStandardInput = true;
...
p.StandardInput.Write("\n");

..或读取异步,以便您可以在 cmd 等待您的输入时获取输出:

p.BeginOutputReadLine();
p.OutputDataReceived += (_, e) => Console.WriteLine(e.Data);

关于c# - 在C#中发送cmd命令并读取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649282/

相关文章:

c# - 如何从 float 计算纵横比

c# - asp 中继器复选框状态保留

java - 如何生成具有继承权限的进程

c# - 主窗体关闭后应用程序进程不退出 - 使用 ApplicationContext

vb.net - VB 是否可以读取仍在运行的 CMD 中运行的程序的每一行输出?

windows - 如何在 cmd 窗口中使用 Windows dir 命令仅列出 .doc 或 .xls 文件?

c# - Windows Phone 8.1 应用程序无法在 Windows 10 设备上准确运行

c# - 在c#中逐行读取大文件

c - 多进程服务器UDP套接字比单进程慢?

windows - 如何使用批处理文件获取文件的属性