首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 取得應用程式目錄與執行路徑的 7 種方法比較

     編輯:關於C語言

方法對照表

方法回傳值範例適用場景備註
Process.GetCurrentProcess().MainModule.FileNameC:\MyApp\bin\Debug\MyApp.exe取得完整執行檔路徑需 using System.Diagnostics;,可能需管理員權限
Environment.CurrentDirectoryC:\MyApp\bin\Debug目前工作目錄 (可讀寫)可被 Directory.SetCurrentDirectory 改變
Directory.GetCurrentDirectory()C:\MyApp\bin\Debug同上,靜態方法同上,非執行檔所在目錄
AppDomain.CurrentDomain.BaseDirectoryC:\MyApp\bin\Debug\應用程式基底目錄 (含結尾斜線)最常用,ASP.NET/WinForms/Console 通用
AppDomain.CurrentDomain.SetupInformation.ApplicationBaseC:\MyApp\bin\Debug\同 BaseDirectory屬性較深,建議用 BaseDirectory
Application.StartupPathC:\MyApp\bin\DebugWinForms 專用,啟動路徑 (無結尾斜線)需參考 System.Windows.Forms
Application.ExecutablePathC:\MyApp\bin\Debug\MyApp.exeWinForms 專用,完整執行檔路徑同上

關鍵差異圖解

專案結構:
C:\MyProject\bin\Debug\MyApp.exe
                └─ Config.xml

執行情境:在 C:\Temp 執行 "C:\MyProject\bin\Debug\MyApp.exe"

結果比較:
Environment.CurrentDirectory           → C:\Temp          (啟動時的工作目錄)
Directory.GetCurrentDirectory()        → C:\Temp          (同上)
AppDomain.CurrentDomain.BaseDirectory  → C:\MyProject\bin\Debug\  (執行檔實際所在)
Application.StartupPath                → C:\MyProject\bin\Debug   (WinForms 專用)
Process...MainModule.FileName          → C:\MyProject\bin\Debug\MyApp.exe

最佳實踐建議

  1. 通用專案 (含 ASP.NET Core):使用 AppDomain.CurrentDomain.BaseDirectory 或 .NET Core 的 AppContext.BaseDirectory。
  2. WinForms / WPF 桌面應用:Application.StartupPath (WinForms) 或 System.Reflection.Assembly.GetEntryAssembly().Location。
  3. 需載入同目錄設定檔:Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml")。
  4. 避免使用:Environment.CurrentDirectory,因使用者可透過「捷徑屬性 → 開始位置」改變它。

跨平台 .NET Core / .NET 5+ 寫法

// 取得執行檔目錄 (不含檔名)
string baseDir = AppContext.BaseDirectory;  // 等同 BaseDirectory,含結尾斜線

// 取得執行檔完整路徑
string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

// 取得專案根目錄 (開發時期常用,透過尋找 .csproj 或 .sln)
public static string GetProjectRoot() {
    string dir = AppContext.BaseDirectory;
    while (!Directory.GetFiles(dir, "*.csproj").Any() && !Directory.GetFiles(dir, "*.sln").Any()) {
        dir = Directory.GetParent(dir)?.FullName;
        if (dir == null) throw new DirectoryNotFoundException("找不到專案根目錄");
    }
    return dir;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved