How to print the name of the method, file and line that was called?

Asked

Viewed 111 times

2

Example:

file name: teste.cs

A part of the code:

...

public void MeuMetodo()
{
    // suponha que essa linha seja a 100
    Console.WriteLine("Arquivo: " + arquivo + "Metodo: " + metodo +" linha: " + linha);
    //Resultado seria: Arquivo: teste.cs Metodo: MeuMetodo linha: 101
    //
    //mais codigos
}

1 answer

5


Use the class StackFrame.

sf.GetFileName(), sf.GetMethod(), sf.GetFileLineNumber()

If there’s a way release this information will not be available. There are techniques that can help, but in general are not worth, almost always only use this thrashing.

You can also create a method like this:

public static void MostraMetodo([CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null) {
    WriteLine($"File: {sourceFilePath}, Method {caller}, Line: {lineNumber} ");
}

I put in the Github for future reference.

Where to call this method is what will be shown. See the documentation.

There must be other techniques.

  • 1

    You can get the class name using this.GetType().Name and the method name using MethodBase.GetCurrentMethod().Name at least this information you can get in release.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.