简体   繁体   中英

How can we get argv[0] in C#?

With C/C++, we can get argv[0]:

printf("%s\n",argv[0])

In C#, args begins with argv[1].

Non of bellow API gives exactly argv[0], at least under Linux:

AppDomain.CurrentDomain.FriendlyName: only gives the name, no path
Process.GetCurrentProcess().ProcessName: gives wrong result with symbol link, and no path
Process.GetCurrentProcess().MainModule.FileName:  gives wrong result with symbol link, and the path is always absolute

FYI: under Linux with the above C/C++ code (whose result is treated as the golden standard here), it prints the exact path (absolute or relative) that is used to invoke the program, and if you invoke the program through any symbol link, the symbol link's name is printed instead of the real program.

I ask this question since I try to write a wrapper program using C# under Ubuntu, which should pass argv[0] through to be fully transparent in case the wrapped program's behavior depends on argv[0].

Environment.CommandLine and Environment.GetCommandLineArgs() should contain the full and unmodified command line.

The accepted answer doesn't work for me on .NET 5 on Linux, I get $PROJECT_DIRECTORY/bin/Debug/net5.0/$PROJECT_NAME.dll . Further, this doesn't change if symlinks are used.

Instead I have to use this non-portable hack (taken from this comment):

(await File.ReadAllTextAsync("/proc/self/cmdline")).Split('\0')[0]

Result:

$ bin/Debug/net5.0/bpm
argv[0]: bin/Debug/net5.0/bpm
$ ln -s bin/Debug/net5.0/bpm foo
$ ./foo
argv[0]: ./foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM