[英]How can we get argv[0] in C#?
With C/C++, we can get argv[0]:使用 C/C++,我们可以获得 argv[0]:
printf("%s\n",argv[0])
In C#, args begins with argv[1].在 C# 中,args 以 argv[1] 开头。
Non of bellow API gives exactly argv[0], at least under Linux: Non of bellow API 给出了 argv[0],至少在 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.仅供参考:在 Linux 下使用上述 C/C++ 代码(其结果在这里被视为黄金标准),它打印用于调用程序的确切路径(绝对或相对),如果您通过任何符号调用程序链接,符号链接的名称被打印而不是真正的程序。
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].我问这个问题是因为我尝试在 Ubuntu 下使用 C# 编写包装程序,如果包装程序的行为取决于 argv[0],它应该传递 argv[0] 以完全透明。
Environment.CommandLine
and Environment.GetCommandLineArgs()
should contain the full and unmodified command line. Environment.CommandLine
和Environment.GetCommandLineArgs()
应包含完整且未修改的命令行。
The accepted answer doesn't work for me on .NET 5 on Linux, I get $PROJECT_DIRECTORY/bin/Debug/net5.0/$PROJECT_NAME.dll
.接受的答案在 Linux 上的 .NET 5 上对我不起作用,我得到
$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):相反,我必须使用这个不可移植的 hack(取自这个评论):
(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.