如何在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.
廣告