使用C#和获得信息到字符串运行shell命令 [英] Run shell commands using c# and get the info into string

查看:227
本文介绍了使用C#和获得信息到字符串运行shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行在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#

推荐答案

您可以重定向与<一个输出href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx">ProcessStartInfo.有一个关于<一个例子href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx">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.

这篇关于使用C#和获得信息到字符串运行shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆