Created
May 22, 2020 18:39
-
-
Save korchoon/10392827367590b5cc2fb07b32282a6f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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