【问题标题】:How to get and set variables from console application如何从控制台应用程序获取和设置变量
【发布时间】:2020-01-06 13:12:20
【问题描述】:

我有一个 .net 应用程序,它使用以下代码调用 .net 核心应用程序:

Process p = new Process();
var startInfo = p.StartInfo;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "myDotNetCoreApp.exe";
startInfo.Arguments = arguments;
startInfo.CreateNoWindow = true;
p.OutputDataReceived += P_OutputDataReceived;
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();

如您所见,我正在控制台应用程序的 Main 方法中设置字符串 (argument),我得到的结果如下:

  static void Main(string[] args)
  {
    var inputCommands = args[0].Split(",");
    ...
  }

另外,我捕捉到Console.WriteLine()“事件”并做一些动作。我在控制台应用程序中有一个方法,它返回 bool 类型。现在从 .net 应用程序中,我需要知道该方法返回了什么结果。我可以像Console.WriteLine("Method returned true") 那样做,但它不喜欢我。还有另一种方法可以做到这一点吗?

【问题讨论】:

  • 请分享 .NET 核心应用程序
  • exe 的返回值是退出代码。请参阅:docs.microsoft.com/en-us/dotnet/api/…
  • ^--- 这与System.Environment.Exit(YourExitCode); 一起使用特定代码关闭被调用程序或static int Main(...) { ... return YourExitCode; }
  • @Cid 好的,我如何从进程中获取 YourExitCode?​​span>
  • @DIlshodK 检查 jdwend 提供的链接

标签: c# .net .net-core process console-application


【解决方案1】:

来自@Cid 的评论:

在您的 myDotNetCoreApp 应用中,使用以下命令关闭您的应用:

System.Environment.Exit(0)

0 表示您的应用已成功关闭

然后使用它从 myDotNetCoreApp 获取信息

Process p = new Process();
var startInfo = p.StartInfo;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "myDotNetCoreApp.exe";
startInfo.Arguments = arguments;
startInfo.CreateNoWindow = true;
p.OutputDataReceived += P_OutputDataReceived;
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
if(p.ExitCode==0){
//Do some...
}

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多