4

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.

Sphinx
  • 109
  • 1
  • 13
  • I'm assuming you have an issue on a remote computer that you need to trace out? In that case its better to use the Visual Studio Remote Debugging Tools (https://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx). I'm not sure its possible to get the actual source lines easily, but the information is in the PDB files. Its entirely different to include variable values and such though. – Ron Beyer Jun 08 '15 at 16:28
  • See http://stackoverflow.com/questions/8614157/current-possibilities-for-tracing-program-flow-in-c – Sergey Vlasov Jun 09 '15 at 03:18

1 Answers1

0

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...

CSharpie
  • 9,195
  • 4
  • 44
  • 71
  • Interesting, but works strange and not as i expected. It shows every line, even commented ones. Very important - it does not step into functions. And somehow shows lines from unreachable code (outdated functions with 0 references) if on the same page between BeginTrace() ... EndTrace(). – Sphinx Jun 09 '15 at 07:14