如何在 C# 中获取当前可执行文件的名称?
有几种方法可以在C#中获取当前可执行文件的名称。
使用System.AppDomain-
应用程序域提供了在不同应用程序域中运行的代码之间的隔离。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进程都包含至少一个线程来处理应用程序的执行。进程可以有多个线程,它们可以加快执行速度并提供更多响应,但包含单个主执行线程的进程被认为是线程安全的。
此方法返回不带扩展名的文件名(例如:应用程序)。
示例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.
热门推荐
10 最美婆婆生日祝福语简短
11 妹妹生日祝福语简短唯美
12 春季祝福语女生文案简短
13 新房开工吉日祝福语简短
14 男士送花祝福语大全简短
15 永远漂亮祝福语女生简短
16 中秋祝福语送朋友简短
17 玫瑰礼盒祝福语大全简短
18 虎年开新车祝福语简短