如何在C#中获取当前可执行文件的名称?
在C#中,有几种方法可以获取当前可执行文件的名称。
使用System.AppDomain −
应用程序域提供在不同应用程序域中运行的代码之间的隔离。应用程序域是代码和数据的逻辑容器,就像进程一样,具有独立的内存空间和对资源的访问权限。应用程序域也像进程一样充当边界,以避免任何意外或非法的尝试从一个正在运行的应用程序访问另一个应用程序中对象的數據。
System.AppDomain 类为我们提供了处理应用程序域的方法。它提供创建新的应用程序域、从内存中卸载域等方法。
此方法返回带有扩展名的文件名(例如:Application.exe)。
示例
using System;
namespace DemoApplication{
public class Program{
public static void Main(){
string currentExecutable =
System.AppDomain.CurrentDomain.FriendlyName;
Console.WriteLine($"Current Executable Name: {currentExecutable}");
Console.ReadLine();
}
}
}输出
以上代码的输出是
Current Executable Name: MyConsoleApp.exe
使用System.Diagnostics.Process −
进程是一个操作系统概念,它是Windows操作系统提供的最小隔离单元。当我们运行一个应用程序时,Windows会为该应用程序创建一个具有特定进程ID和其他属性的进程。每个进程都分配了必要的内存和一组资源。
每个Windows进程至少包含一个线程,负责应用程序的执行。一个进程可以有多个线程,它们可以加快执行速度并提高响应能力,但是包含单个主执行线程的进程被认为更线程安全。
此方法返回不带扩展名的文件名(例如:Application)。
示例1
using System;
namespace DemoApplication{
public class Program{
public static void Main(){
string currentExecutable =
System.Diagnostics.Process.GetCurrentProcess().ProcessName;
Console.WriteLine($"Current Executable Name: {currentExecutable}");
Console.ReadLine();
}
}
}输出
以上代码的输出是
Current Executable Name: MyConsoleApp
示例2
using System;
namespace DemoApplication{
public class Program{
public static void Main(){
string currentExecutable =
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
Console.WriteLine($"Current Executable Name: {currentExecutable}");
Console.ReadLine();
}
}
}输出
以上代码的输出是
Current Executable Name: C:\Users\UserName\source\repos\MyConsoleApp\MyConsoleApp\bin\Debug\MyCo nsoleApp.exe In the above example we could see that Process.GetCurrentProcess().MainModule.FileName returns the executable file along with the folder.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP