C# trace (log) all code lines between two points

2.2k views Asked by At

Is it possible in VS 2013 (C#) trace (to a file) execution path of my app? I mean line-by-line, somewhere about as if i were pressing F11 all the time after a breakpoint, writing down lines manually... Resulting log may be huge, i know, but nevertheless?

Of course i want source code lines, not MSIL.

1

There are 1 answers

1
CSharpie On

Yes this is possible, however this requires access to the sourcefile, if you really need the sourcecode.

Use the CallerInformationAttributes

C# 4.5 Required:

int _beginIndex;

public void BeginTrace(
    [CallerFilePath] string sourceFilePath = "",
    [CallerLineNumber] int sourceLineNumber = 0)
{ 
    _beginIndex = sourceLineNumber;
}

public void EndTrace(
    [CallerFilePath] string sourceFilePath = "",
    [CallerLineNumber] int sourceLineNumber = 0)
{
    int index = 0;
    foreach(var line in File.ReadLines(sourceFilePath))
    {
       if(index++ > _beginIndex && index <sourceLineNumber)
           Console.WriteLine(line);
    }
}

Then use it like this:

  BeginTrace();

  Foo foo = new Foo();
  foo.DoSomeStuff();
  foo.Bar();

  EndTrace();

This example only works with Begin and End in the same File though, aynthing else will be really hard to accomplish unless you pass some object arround...