Getting the Stacktrace

我只是一个虾纸丫 提交于 2019-11-28 12:22:49
David Pokluda

When you catch an exception you can construct StackTrace object and extract useful information from it. See the following example:

        StackTrace st = new StackTrace(true);
        for(int i =0; i< st.FrameCount; i++ )
        {
            // Note that high up the call stack, there is only
            // one stack frame.
            StackFrame sf = st.GetFrame(i);
            Console.WriteLine();
            Console.WriteLine("High up the call stack, Method: {0}",
                sf.GetMethod());

            Console.WriteLine("High up the call stack, Line Number: {0}",
                sf.GetFileLineNumber());
        }

PS: This works even without an exception -- see How to print the current stack trace in .NET without any exception.

You can print out the stacktrace at any time by calling Environment.StackTrace

string tracktrace = System.Environment.StackTrace;

System.Environment.StackTrace is an awesome tool, but be aware that you don't always get what you're looking for and there are differences between x86 and x64 platforms that can affect the output. Grody details here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!