优质中文开源软件代码项目资源技术共享平台
传播开源的理念,推广开源项目
学习是对自己最棒的投资!与君共勉!
云服务器主机测评推荐,开源软件代码项目技术资源共享!

网站首页 > 主流语言 > C/C#/C++ 正文

C#中通过Process运行程序如何获取进程的标准输出

longtao100 2023-11-13 09:08:05 C/C#/C++ 8 ℃ 0 评论

在用C#写一个项目中的工具程序时,需要在C#程序中运行一个命令行的程序,同时将程序的命令行标准输出获取到并显示在指定的文本框中。
查找相关资料找到以下办法,供大家参考。
在创建Process的时候,通过如下方式来实现该功能。
首先,创建ProcessStartInfo:

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

然后,用上面创建好的启动信息来启动进程,如下:

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

另外,也可以参照以下代码,采用同步或异步方式来运行程序,获取命令行标准输出的内容。
同步方式的代码:

static void runCommand()
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
}

异步方式的代码:

static void runCommand() 
{
//* Create your Process
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c DIR";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
//* Start process and handlers
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
//* Do your stuff with the output (write to console/log/StringBuilder)
Console.WriteLine(outLine.Data);
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

请填写验证码
开源分类
最近发表
开源网标签
开源网归档