在 C# 中发送 cmd 命令并读取结果
Posted
技术标签:
【中文标题】在 C# 中发送 cmd 命令并读取结果【英文标题】:Sending cmd commands and reading results in C# 【发布时间】:2014-08-30 05:15:46 【问题描述】:我想发送带有参数的命令并从 cmd 读取它们的答案。所以,我写了下面的代码,但它不起作用并锁定在屏幕上(myString 通常为空 - “”)。我只想将命令发送到打开的命令提示符。问题出在哪里?提前致谢。 (例如:如何获取 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();
【问题讨论】:
Q1 Q2 可能会有所帮助。 尝试了此代码并按预期工作。但是,如果没有 /T 标志,命令外壳会提示您插入新日期。 【参考方案1】: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);
【讨论】:
【参考方案2】:此代码可能对您有所帮助
string strOutput;
//Starting Information for process like its path, use system shell i.e. control process by system etc.
ProcessStartInfo psi = new ProcessStartInfo(@"C:\WINDOWS\system32\cmd.exe");
// its states that system shell will not be used to control the process instead program will handle the process
psi.UseShellExecute = false;
psi.ErrorDialog = false;
// Do not show command prompt window separately
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
//redirect all standard inout to program
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
//create the process with above infor and start it
Process plinkProcess = new Process();
plinkProcess.StartInfo = psi;
plinkProcess.Start();
//link the streams to standard inout of process
StreamWriter inputWriter = plinkProcess.StandardInput;
StreamReader outputReader = plinkProcess.StandardOutput;
StreamReader errorReader = plinkProcess.StandardError;
//send command to cmd prompt and wait for command to execute with thread sleep
inputWriter.WriteLine("C:\\PLINK -ssh root@susehost -pw opensuselinux echo $SHELL\r\n");
Thread.Sleep(2000);
// flush the input stream before sending exit command to end process for any unwanted characters
inputWriter.Flush();
inputWriter.WriteLine("exit\r\n");
// read till end the stream into string
strOutput = outputReader.ReadToEnd();
//remove the part of string which is not needed
int val = strOutput.IndexOf("-type\r\n");
strOutput = strOutput.Substring(val + 7);
val = strOutput.IndexOf("\r\n");
strOutput = strOutput.Substring(0, val);
MessageBox.Show(strOutput);
【讨论】:
以上是关于在 C# 中发送 cmd 命令并读取结果的主要内容,如果未能解决你的问题,请参考以下文章
使用带有 C# 的 XmlDocument 读取 XML 数据 - 读取属性数据并拆分结果