【问题标题】:Error handling using process c#使用进程 c# 处理错误
【发布时间】:2016-09-02 12:26:54
【问题描述】:

我使用 C# 创建了一个控制台应用程序,并使用 Process 从另一个 Windows 窗体应用程序调用它。

以下是我的控制台应用程序代码

   static void Main(string[] args)
        {
            try
            {
                // ...my code
            }
            catch (Exception)
            {

                throw;
            }
        }

以下是使用进程从窗口应用程序调用控制台应用程序的exe的代码

    public void CallExe()
    {
        try
        {                              
            Process proc = new Process();
            proc.StartInfo.FileName = @"D:\Debug\console1.exe";
            proc.StartInfo.Arguments = "My args";
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.Start();              
            proc.WaitForExit();              
            string stdout = proc.StandardOutput.ReadToEnd();
            string stderr = proc.StandardError.ReadToEnd();
            proc = null;
        }

        catch (Exception ex)
        {

            throw ex;
        }
    }

现在,我想要的是当控制台应用程序出现任何错误时 它直接抛出到我的窗口应用程序捕获块。或者我可以在控制台应用程序抛出的窗口应用程序中收到错误消息吗?

【问题讨论】:

  • 您无法捕获另一个进程中发生的错误,但您可以从控制台应用返回退出代码。
  • 我可以从控制台应用程序中获取 ex.message 吗?
  • 你可以specify an exit code是一个整数,从Process.ExitCode取。或者你可以从/向 StandardOutput 或 StandardError 读/写任何你想要的东西
  • 你可以做的是进程间通信:在你的控制台进程中捕获异常,有一个到你的另一个进程的管道,然后在那个管道上写一个序列化的异常......在另一边阅读它,并且... 甚至可能就下一步做什么给出命令?!

标签: c# error-handling process console-application


【解决方案1】:

您没有从您运行的进程中捕获任何内容。您不能在两个流上调用ReadToEnd,因为它会阻止其中一个或另一个产生结果。如果您想将两个标准输出都捕获为标准错误,您需要订阅 DataReceived 事件并存储来自事件参数的数据。

您的 Windows 窗体应用程序中的以下代码应如下所示:

Process proc = new Process();
proc.StartInfo.FileName = @"console.exe";
proc.StartInfo.Arguments = "My args";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

//store outcome of process
var errors = new StringBuilder();
var output = new StringBuilder();
var hadErrors = false;

// raise events
proc.EnableRaisingEvents = true;

// capture normal output
proc.OutputDataReceived += (s, d) => { 
    output.Append(d.Data); 
};

// Capture error output
proc.ErrorDataReceived += (s, d) => { 
    if (!hadErrors)
    {
        hadErrors = !String.IsNullOrEmpty(d.Data);
    }
    errors.Append(d.Data); 
};

proc.Start();
// start listening on the stream
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();

proc.WaitForExit();
string stdout = output.ToString();
string stderr = errors.ToString();

if (proc.ExitCode !=0 || hadErrors)
{
    MessageBox.Show("error:" + stderr);
}

在测试控制台应用程序中,您现在可以写入 stderr 并根据需要设置退出代码:

try
{
    Console.WriteLine("Ready ...");
    var cmd = Console.ReadLine();
    if (cmd == "e")
    {
        throw new Exception("boom");
    } else
    {
        Console.WriteLine("success!");
    }
    Environment.ExitCode = 0;
}
catch(Exception e)
{
    // write to stderr
    Console.Error.WriteLine(e.Message);
    // exit code to 1
    Environment.ExitCode = 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2011-09-18
    • 1970-01-01
    相关资源
    最近更新 更多