Say I have a method PrintSourceCode(Action action)
that accepts an Action delegate and is executed this way:
PrintSourceCode(() =>
{ // need this line number
DoSomething();
})
Within PrintSourceCode
I would like to print the source code of the action passed.
I was able to get the StackFrame
, then read the source file and output it. However it produces the output of the entire PrintSourceCode()
call rather that just the action.
static void PrintSourceCode(Action action)
{
action();
var mi = action.GetMethodInfo(); // not currently used
var frame = new StackFrame(1, true);
var lineNumber = frame.GetFileLineNumber();
var fileName = frame.GetFileName();
var lines = File.ReadAllLines(fileName);
var result = new StringBuilder();
for (var currLineIndex = lineNumber - 1; currLineIndex < lines.Length; currLineIndex++)
{
var currentLine = lines[currLineIndex];
result.AppendLine(currentLine);
if (Regex.IsMatch(currentLine, @";\s*$"))
{
break;
}
}
Console.WriteLine(result.ToString());
}
Current output
PrintSourceCode(() =>
{
DoSomething();
Desired output
{
DoSomething();
}
I can call action.GetMethodInfo()
however that doesn't seem to have the file/line information. And there is no way to get/construct the StackFrame because the action
is not running.
Is there a way to get the file/line of an action from the outside of the action itself?