【问题标题】:Run shell commands using C# and get the info into string [duplicate]使用 C# 运行 shell 命令并将信息转换为字符串 [重复]
【发布时间】:2013-03-05 21:26:40
【问题描述】:

我想从 C# 运行一个 shell 命令并在我的程序中使用返回的信息。 所以我已经知道要从终端运行某些东西,我需要这样做:

string strCmdText;
strCmdText= "p4.exe jobs -e";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);

所以现在执行命令,并从该命令返回一些信息... 我的问题是如何在我的程序中使用这些信息,可能与命令行参数有关,但不确定。

我真的需要使用 C#。

【问题讨论】:

标签: c# .net shell


【解决方案1】:

您可以使用ProcessStartInfo 重定向输出。在MSDNSO 上有示例。

例如

Process proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

然后启动进程并从中读取:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

根据您要完成的工作,您还可以取得更多成就。我编写了将数据异步传递到命令行并从中读取的应用程序。这样的例子不容易发布在论坛上。

【讨论】:

  • 完美!谢谢布赖恩!
  • 这太完美了!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
相关资源
最近更新 更多