Skip to content

Instantly share code, notes, and snippets.

@korchoon
Created May 22, 2020 18:39
Show Gist options
  • Save korchoon/10392827367590b5cc2fb07b32282a6f to your computer and use it in GitHub Desktop.
Save korchoon/10392827367590b5cc2fb07b32282a6f to your computer and use it in GitHub Desktop.
public class DebugFileInfo {
Dictionary<StackFrame, string> FrameToLine;
Dictionary<string, string[]> PathToLines;
public DebugFileInfo() {
FrameToLine = new Dictionary<StackFrame, string>();
PathToLines = new Dictionary<string, string[]>();
}
[Conditional("DEBUG")]
public void SetDebugName(ref string target, int skipFrames) {
var withoutFileInfo = new StackTrace(1 + skipFrames, fNeedFileInfo: false).GetFrame(0);
if (TryGetLine(withoutFileInfo, out var line)) {
target = line;
return;
}
var fullFrame = new StackTrace(1 + skipFrames, fNeedFileInfo: true).GetFrame(0);
GetLine(withoutFileInfo, fullFrame, out line);
target = line;
}
bool TryGetLine(StackFrame withoutFileInfo, out string line) {
return FrameToLine.TryGetValue(withoutFileInfo, out line);
}
void GetLine(StackFrame withoutFileInfo, StackFrame withFileInfo, out string line) {
var path = withFileInfo.GetFileName();
if (!PathToLines.TryGetValue(path, out var lines)) {
if (!File.Exists(path)) {
line = default;
return;
}
lines = File.ReadAllLines(path);
PathToLines.Add(path, lines);
}
var fileLineNumber = withFileInfo.GetFileLineNumber();
var s = lines[fileLineNumber - 1];
// line = $"{s.Trim()} | {Path.GetFileName(path)}:{fileLineNumber}";
var col = withFileInfo.GetFileColumnNumber();
line = $"{s.Substring(col - 1).Trim()} [{fileLineNumber}]";
FrameToLine.Add(withoutFileInfo, line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment