public static string GetLastErrorStr() { int MAX_SIZE = 255; StringBuilder buffer = new StringBuilder(MAX_SIZE); string message = string.Empty; int err = 0; try { err = Marshal.GetLastWin32Error(); int retVal = FormatMessage( FORMAT_MESSAGE_DEFAULT, new HandleRef(null, IntPtr.Zero), err, GetUserDefaultLCID(), buffer, MAX_SIZE, new HandleRef(null, IntPtr.Zero)); message = retVal != 0 ? buffer.ToString() : "<error returned>"; } catch (Exception ex) { if (DbgUtil.IsCriticalException(ex)) { throw; //rethrow critical exception. } message = ex.ToString(); } return(string.Format(CultureInfo.CurrentCulture, "0x{0:x8} - {1}", err, message)); }
/// <devdoc> /// Returns information about the top stack frames in a string format. The input param determines the number of /// frames to include. /// </devdoc> public static string StackFramesToStr(int maxFrameCount) { string trace = string.Empty; try { StackTrace st = new StackTrace(true); int dbgUtilFrameCount = 0; // // Ignore frames for methods on this library. // Note: The stack frame holds the latest frame at index 0. // while (dbgUtilFrameCount < st.FrameCount) { StackFrame sf = st.GetFrame(dbgUtilFrameCount); if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil)) { break; } dbgUtilFrameCount++; } maxFrameCount += dbgUtilFrameCount; // add ignored frames. if (maxFrameCount > st.FrameCount) { maxFrameCount = st.FrameCount; } for (int i = dbgUtilFrameCount; i < maxFrameCount; i++) { StackFrame sf = st.GetFrame(i); if (sf == null) { continue; } MethodBase mi = sf.GetMethod(); if (mi == null) { continue; } string args = string.Empty; string fileName = sf.GetFileName(); int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\'); if (backSlashIndex != -1) { fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1); } foreach (ParameterInfo pi in mi.GetParameters()) { args += pi.ParameterType.Name + ", "; } if (args.Length > 0) // remove last comma. { args = args.Substring(0, args.Length - 2); } trace += string.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args); } } catch (Exception ex) { if (DbgUtil.IsCriticalException(ex)) { throw; //rethrow critical exception. } trace += ex.ToString(); } return(trace.ToString()); }