salpenza
salpenza

Reputation: 37

Unknown cause of InvalidOperationException?

I have a string array that I use to split output from another process. I then want to display the first element of that array in a textbox in my WPF interface. However, I receive this exception when I try to do so, any ideas of how to fix it?

        output = p.StandardOutput.ReadToEnd();
        code = p.ExitCode;
        p.WaitForExit();
        string[] result = this.output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        this.outputList.Add(Convert.ToDouble(result[0]));
        this.MyTextBox.Text = result[0];

Upvotes: 1

Views: 67

Answers (1)

Tam Bui
Tam Bui

Reputation: 3038

The InvalidOperationException should tell you exactly which line of code caused the exception. Put a try/catch around your code and then read the StackTrace property to get the line of code causing the problem.

try
{
    output = p.StandardOutput.ReadToEnd();
    code = p.ExitCode;
    p.WaitForExit();
    string[] result = this.output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

    // If you are updating UI controls, make sure you are doing it only on the UI thread.  The 'Dispatcher' will make sure the code inside is run on the UI thread.
    this.Dispatcher.Invoke(() =>
    {
        this.outputList.Add(Convert.ToDouble(result[0]));
        this.MyTextBox.Text = result[0];
    });
}
catch (InvalidOperationException ex)
{
    // You don't need this line, you can just put a breakpoint here to debug the problem by reading the properties of the 'ex' variable.
    this.MyTextBox.Text = $"{ex.Message}\n{ex.StackTrace}";
}

Upvotes: 1

Related Questions