1

How to get the StackTrace similar to Exception.ToString()?

According to this answer it should be Environment.StackTrace - but I get different results for both methods.

Below is a simplified example. I have seen cases with Environment.StackTrace having +160 lines more then Exception.ToString().

These lines seems to be mainly underlying framework things like related to tasks etc, and I'm in no need for them.

Is it possible to get the exact same formatting as Exception.ToString()?

namespace ConsoleApp2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await Task.Delay(0);

            string fromStackTrace   = Environment.StackTrace;
            string fromException;

            try
            {
                throw new Exception("Test");
            }
            catch (Exception e)
            {
                fromException = e.ToString();
            }
        }
    }
}

Result fromException:

System.Exception: Test
   at ConsoleApp2.Program.Main(String[] args) in C:\Temp\C#\ConsoleApp2\ConsoleApp2\Program.cs:line 17

Result fromStackTrace:

   at System.Environment.get_StackTrace()
   at ConsoleApp2.Program.Main(String[] args) in C:\Temp\C#\ConsoleApp2\ConsoleApp2\Program.cs:line 12
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at ConsoleApp2.Program.Main(String[] args)
   at ConsoleApp2.Program.<Main>(String[] args)
Dirk Boer
  • 8,522
  • 13
  • 63
  • 111
  • Exception in `catch` is [unwinded](https://en.wikipedia.org/wiki/Call_stack#Unwinding), that's why it's shorter, because it finds handler. – Sinatr Jun 17 '20 at 14:22
  • Does this answer your question? [.Net - what is an "unwind"?](https://stackoverflow.com/questions/2005606/net-what-is-an-unwind) – Sinatr Jun 17 '20 at 14:23

0 Answers0