使用 C# 运行 shell 命令并将信息转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15234448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run shell commands using C# and get the info into string
提问by inside
I want to run a shell command from C# and use the returning information inside my program. So I already know that to run something from terminal I need to do something like that:
我想从 C# 运行一个 shell 命令并在我的程序中使用返回的信息。所以我已经知道要从终端运行一些东西,我需要做这样的事情:
string strCmdText;
strCmdText= "p4.exe jobs -e";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
so now command executed, and from this command some information is returned... My question is how can use this information in my program, probably something to do with command line arguments, but not sure.
所以现在执行命令,并从这个命令返回一些信息......我的问题是如何在我的程序中使用这些信息,可能与命令行参数有关,但不确定。
I really need to use C#.
我真的需要使用 C#。
采纳答案by P.Brian.Mackey
You can redirect the output with ProcessStartInfo. There's examples on MSDNand SO.
您可以使用ProcessStartInfo重定向输出。MSDN和SO上有示例。
E.G.
例如
Process proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
then start the process and read from it:
然后启动该过程并从中读取:
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
string line = proc.StandardOutput.ReadLine();
// do something with line
}
Depending on what you are trying to accomplish you can achieve a lot more as well. I've written apps that asynchrously pass data to the command line and read from it as well. Such an example is not easily posted on a forum.
根据您要实现的目标,您还可以实现更多目标。我编写了将数据异步传递到命令行并从中读取数据的应用程序。这样的例子不容易发布在论坛上。