使用C#和获得信息到字符串运行shell命令字符串、命令、信息、shell

由网友(埋葬幸福)分享简介:我想运行在C#中的shell命令,并使用我的程序中返回的信息。所以,我已经知道,从运行终端东西,我需要做这样的事情I want to run a shell command from c# and use the returning information inside my program.So I alrea...

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

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

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...

我知道,它更容易使用脚本语言如Python做到这一点,但确实需要使用C#

I know that it much easier to do it with script languages such as python, but really need to use c#

推荐答案

您可以重定向与ProcessStartInfo.有一个关于MSDN和 SO 。

You can redirect the output with ProcessStartInfo. There's examples on MSDN and SO.

例如。

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
}

根据您所要完成就可以实现很多的还有很多的东西。我已经写了asynchrously数据传递到命令行并读取它,以及应用程序。这样的例子并不容易贴在了论坛。

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.

阅读全文

相关推荐

最新文章