1

I used the following code to get the name of the source code's file

StackTrace trace = new StackTrace(true);
string fileName = string.Empty;
foreach (var frame in trace.GetFrames())
{
    string fileToCheck = frame.GetFileName();
    if (someLogicToCheckTheSuitableFile())
    {
        fileName = fileToCheck;
        break;
    }
}

When I ran it at my local server, it worked well. But when I tried it at my linux server, the function "GetFileName" always returns null. Can somebody give me an advice?

  • You might not have that name because of either a release build stripping that or the hosting enviroment doesn't allow it. – Berkays Jan 19 '22 at 01:01

1 Answers1

1

StackFrame.GetFileName Method

public virtual string? GetFileName ();

Gets the file name that contains the code that is executing. This information is typically extracted from the debugging symbols for the executable. source

Full example you can finde here

After you build your application VS created pdb file (in release or debug), containing information about code call and links to your code files. This information stores in ***.pdb files which located in the same folder as executable file. You can experiment with your app (or MS Example as I linked in 2): build it in debug/release and run application from cmd/PS with *.pdb file and without. When pdb file exists - you will see link to code file, after you delete pdb file - no information will be presented about your code.

You can disable/enable creating pdb files as mentioned here

Maxim
  • 854
  • 1
  • 8
  • 16
  • Thank you for your reply! I tried to set "Portable" to "Debugging Information". The csproj file is as the follow: portable true It woked at my local server, but at the linux server, it's still null – THANH SON T. Jan 19 '22 at 04:42
  • 'Portable' (cross-platform) is new format of 'Full' (wich only for Windows). Does the .pdb file exist on your linux server near your .exe? – Maxim Jan 19 '22 at 05:15
  • I checked it. It exists. – THANH SON T. Jan 19 '22 at 06:13
  • The .pdb file near the .dll file, but the result is still null – THANH SON T. Jan 19 '22 at 07:23
  • I think there is one of this problems: pdb file not from the same app build (newer or older then executable), or format pdb file not match to app. If you will build and execute with pdb file MS example on linux server and you will see information from pdb, that means yor pdb for app executable not correct. Otherwise you should add information about build and production environments to answer more properly – Maxim Jan 19 '22 at 08:46