如何解决来自 C# 控制台应用程序的标准输出字符串
我有一个用 C# 编写的 .Net Framework 控制台应用程序,它是从 Powershell 脚本运行的。作为运行控制台应用程序的结果,我希望能够从控制台应用程序获取值。
举个粗略的例子,我有这个......
namespace PlainConsoleApp
{
class Program
{
static int Main(string[] args)
{
int result = 0;
switch (args[0])
{
case "one":
result = 1;
break;
case "two":
result = 2;
break;
default:
result = -1;
break;
}
return result;
}
}
}
这是使用以下 Powershell 脚本运行的(我对 Powershell 非常陌生):
$consoleApp = "C:\Temp\PlainConsoleApp.exe"
$arg1 = "one"
$submitprocess = start-process $consoleApp $arg1 -Wait -Passthru -NoNewWindow
$result = $submitprocess.ExitCode
Write-Host "exit code: " + $result
exit $submitprocess.ExitCode
所以,当我运行它时,我可以看到我在 ExitCode
中得到了返回结果...但是我被建议查看 $p.StandardOutput.ReadToEnd()
。如果我然后尝试运行这样的东西:
$consoleApp = "C:\Temp\PlainConsoleApp.exe"
$arg1 = "one"
$pinfo = New-Object System.Diagnostics.processstartinfo
$pinfo.FileName = $consoleApp
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $arg1
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode
我似乎仍然只从 ExitCode
获得返回值。另外,我希望能够返回 bool 或字符串,但似乎只能从控制台应用程序返回整数??
对此的任何帮助或建议将不胜感激!
解决方法
我已将控制台应用程序更改为如下所示:
static void Main(string[] args)
{
string result;
switch (args[0])
{
case "1":
result = "one";
break;
case "2":
result = "two";
break;
case "3":
result = "three";
break;
case "4":
result = "four";
break;
case "5":
result = "five";
break;
default:
result = "null";
break;
}
Console.Out.Write(result);
}
现在像这样调用应用程序:
$console = "C:\Dev\Local Projects\PlainConsoleApp\PlainConsoleApp\bin\Debug\PlainConsoleApp.exe"
$arg1 = "5"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $console
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $arg1
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
Write-Host "stdout:" $p.StandardOutput.ReadToEnd()
这似乎可以完成工作:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。