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

2

Example:

filename: teste.cs

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
}
    
asked by anonymous 05.01.2018 / 12:14

1 answer

5

Use the class StackFrame . .

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

If you are in a release mode this information will not be available. There are techniques that can help, but they are usually not worth it, you should almost always only use debugging .

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 placed GitHub for future reference.

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

You should have other techniques.

    
05.01.2018 / 12:24