1

With .NET Core 6, When an unhandled exception occurs in the application, particularly a load error, I want to dump it into a text file and open the default text editor.

The problem is that the text editor gets killed as soon as the app exits!

Process.WaitForExit() doesn't work because I didn't start the app directly, but rather launched the text file.

So far, the best I could do is to wait 10 seconds before exiting the app... how can I do better? Solution needs to work cross-platform.

if (logPath != null)
{
    // Dump error to log file and open default text editor.
    var log = logPath();
    System.IO.File.WriteAllText(log, ex.ToString());
    var notepad = new Process
    {
        StartInfo = new ProcessStartInfo(log)
        {
            UseShellExecute = true
        }
    };
    notepad.Start();
    Thread.Sleep(TimeSpan.FromSeconds(10));
}

EDIT: I'm using Jetbrains Rider in Linux. If I run the application directly outside the IDE, then it stays open!

Etienne Charland
  • 3,424
  • 5
  • 28
  • 58
  • That is extremely unusual. The somewhat more likely explanation is that the IDE you use moved back into the foreground when the program terminated, overlapping the editor window and thus making it look like it quit. – Hans Passant Jul 07 '22 at 15:56
  • Ah! I'm using Jetbrains Rider in Linux. If I run the application directly outside the IDE, then it stays open! – Etienne Charland Jul 07 '22 at 17:33

1 Answers1

-1

The best way to see what happens to your code is using Windows Event Log!

you can simply use it:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

for more help see this title: Write to Windows Application Event Log without event source registration

But if you insist on open text in a default editor like notepad, you can use the below code:

StreamWriter sw = new StreamWriter("tmp_log.txt");
sw.WriteLine("Some errore result to show");
sw.Close();
new Process
{
     StartInfo = new ProcessStartInfo("tmp_log.txt")
     {
        UseShellExecute = true
      }
}.Start();
Hadi
  • 100
  • 1
  • 11
  • That's one option, except that the typical user won't know how to get that info, particularly on Linux and MacOS. I want him to be able to view the problem and copy/paste it to me. – Etienne Charland Jul 07 '22 at 15:18
  • Dear @EtienneCharland! Ok, add another way for you. – Hadi Jul 07 '22 at 15:51
  • The below code is exactly what I posted. Turns out that the problem was JetBrains Rider IDE closing it. If I run the app directly, then it stays open. – Etienne Charland Jul 07 '22 at 17:35
  • I am glad that your problem was solved @EtienneCharland – Hadi Jul 07 '22 at 17:53