C# - print a file name and line number when an exception was thrown

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public static class ExceptionUtils
    {
        public static void PrintException(Exception e)
        {
            var frame = new StackTrace(e, true).GetFrame(0);
            if (frame != null)
            {
                var str = string.Format("File: {0}({1}){2}{3}", frame.GetFileName(), frame.GetFileLineNumber(), Environment.NewLine, e.Message);
                Trace.WriteLine(str);
            }
            else
                Trace.WriteLine(e.Message);
        }
    }