我想要获得当前运行程序的名称,即程序的可执行名称。在C/ c++中,你从args[0]中得到它。


当前回答

System.AppDomain.CurrentDomain.FriendlyName -返回带扩展名的文件名(例如MyApp.exe)。

System.Diagnostics.Process.GetCurrentProcess()。ProcessName -返回没有扩展名的文件名(例如MyApp)。

.MainModule System.Diagnostics.Process.GetCurrentProcess()。FileName -返回完整的路径和文件名(例如C:\Examples\Processes\MyApp.exe)。然后,您可以将此传递到System.IO.Path.GetFileName()或System.IO.Path.GetFileNameWithoutExtension()以实现与上述相同的结果。

其他回答

您可以使用Environment. getcommandlineargs()来获取参数和Environment. getcommandlineargs()。CommandLine获取实际输入的命令行。

此外,您可以使用Assembly.GetEntryAssembly()或Process.GetCurrentProcess()。

但是,在调试时,您应该小心,因为最后一个示例可能会给出调试器的可执行文件名称(取决于您如何附加调试器),而不是可执行文件,其他示例可能也是如此。

System.AppDomain.CurrentDomain.FriendlyName -返回带扩展名的文件名(例如MyApp.exe)。

System.Diagnostics.Process.GetCurrentProcess()。ProcessName -返回没有扩展名的文件名(例如MyApp)。

.MainModule System.Diagnostics.Process.GetCurrentProcess()。FileName -返回完整的路径和文件名(例如C:\Examples\Processes\MyApp.exe)。然后,您可以将此传递到System.IO.Path.GetFileName()或System.IO.Path.GetFileNameWithoutExtension()以实现与上述相同的结果。

在。net Core(或Mono)上,当定义进程的二进制文件是Mono或。net Core (dotnet)的运行时二进制文件,而不是您感兴趣的实际应用程序时,大多数答案都不适用。在这种情况下,使用这个:

var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);

试试这个:

System.Reflection.Assembly.GetExecutingAssembly()

这将返回一个System.Reflection.Assembly实例,其中包含您希望了解的有关当前应用程序的所有数据。我认为Location属性可能会得到你想要的。

System.Reflection.Assembly.GetEntryAssembly()。如果程序集没有从内存中加载,Location返回exe名称的位置。 System.Reflection.Assembly.GetEntryAssembly()。CodeBase以URL的形式返回位置。