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)