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

C# 取得各類路徑完整對照表:執行檔、工作目錄、AppDomain、Web 應用

     編輯:關於C語言

前言

「目前路徑」在不同執行環境(主控台、WinForms、WPF、ASP.NET Core、Windows Service、單一檔案發布)代表完全不同的含義。本文整理 7 種常見 API、適用場景、回傳值差異與最佳實務,附表格速查。

核心 API 對照表

API命名空間回傳範例 (主控台/WinForms)含義適用場景
Process.GetCurrentProcess().MainModule.FileNameSystem.DiagnosticsC:\App\MyApp.exe目前進程執行檔完整路徑需知自身執行檔位置(自更新、啟動參數)
Environment.CurrentDirectorySystemC:\App進程啟動時的工作目錄 (可讀寫)相對路徑解析基準,可被改變
Directory.GetCurrentDirectory()System.IOC:\App同上,靜態方法風格同上,慣用於 IO 操作
AppDomain.CurrentDomain.BaseDirectorySystemC:\App\應用程式基底目錄 (含尾斜線)尋找同目錄下的設定檔、DLL、資源檔
Application.StartupPathSystem.Windows.FormsC:\AppWinForms 應用程式啟動目錄 (無尾斜線)僅限 WinForms,相容 .NET Framework
Application.ExecutablePathSystem.Windows.FormsC:\App\MyApp.exeWinForms 執行檔完整路徑同上
AppDomain.CurrentDomain.SetupInformation.ApplicationBaseSystemC:\App\等同 BaseDirectory進階 AppDomain 設定場景

特殊環境差異

1. 單一檔案發布


// .NET 6+ PublishSingleFile=true
// MainModule.FileName → 臨時解壓路徑 (如 /tmp/.net/MyApp/xyz/MyApp)
// AppDomain.BaseDirectory → 同臨時目錄
// 解決:使用 Assembly.Location (可能為空) 或 IHostEnvironment.ContentRootPath (ASP.NET Core)

2. ASP.NET Core / 一般主機


// Program.cs
var builder = WebApplication.CreateBuilder(args);
// 建議注入 IWebHostEnvironment / IHostEnvironment
app.MapGet("/path", (IWebHostEnvironment env) => 
    new { ContentRoot = env.ContentRootPath, WebRoot = env.WebRootPath });
  • ContentRootPath:專案根目錄 (含 appsettings.json)
  • WebRootPath:wwwroot 靜態檔案目錄

3. Windows Service / 背景服務

  • 工作目錄通常為 C:\Windows\System32,不可信任。
  • 請使用 AppDomain.BaseDirectory 或 IHostEnvironment.ContentRootPath 定位資源。

4. WPF / UWP / MAUI


// WPF
System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
// 或
AppDomain.CurrentDomain.BaseDirectory

// UWP/MAUI (沙盒)
Windows.Storage.ApplicationData.Current.LocalFolder.Path // 本地資料
Windows.ApplicationModel.Package.Current.InstalledLocation.Path // 安裝目錄 (唯讀)

最佳實務:封裝統一路徑服務


public interface IAppPathService
{
    string ExecutablePath { get; }      // 執行檔完整路徑
    string ExecutableDirectory { get; } // 執行檔所在目錄 (含尾斜線)
    string WorkingDirectory { get; }    // 目前工作目錄
    string ContentRoot { get; }         // 內容根目錄 (設定檔、資源)
}

public class AppPathService : IAppPathService
{
    private readonly string _exePath;
    private readonly string _exeDir;
    private readonly string _contentRoot;

    public AppPathService()
    {
        _exePath = Process.GetCurrentProcess().MainModule.FileName;
        _exeDir = Path.GetDirectoryName(_exePath) + Path.DirectorySeparatorChar;
        
        // 單一檔案發布修正
        if (string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location) || 
            _exeDir.Contains("tmp") || _exeDir.Contains("Temp"))
        {
            _exeDir = AppDomain.CurrentDomain.BaseDirectory;
        }

        _contentRoot = _exeDir; // 預設同目錄,ASP.NET Core 可覆寫注入
    }

    public string ExecutablePath => _exePath;
    public string ExecutableDirectory => _exeDir;
    public string WorkingDirectory => Environment.CurrentDirectory;
    public string ContentRoot => _contentRoot;
}

路徑操作安全清單

  1. 永遠使用 Path.Combine、Path.GetFullPath,拒絕字串拼接。
  2. 跨平台注意分隔符:Path.DirectorySeparatorChar / Path.AltDirectorySeparatorChar。
  3. 路徑長度:Windows 260 字元限制,啟用 LongPathsEnabled (登錄表/Group Policy) 或使用 \\?\ 前綴。
  4. 權限:寫入 Program Files、System32 需管理員;優先寫入 Environment.GetFolderPath(SpecialFolder.LocalApplicationData)。
  5. 單元測試:注入 IAppPathService,測試時用 Mock 指定臨時目錄。

快速選型決策樹

  1. 需執行檔路徑 → Process.GetCurrentProcess().MainModule.FileName (修正單一檔案)
  2. 需設定檔/資源目錄 → AppDomain.CurrentDomain.BaseDirectory / IHostEnvironment.ContentRootPath
  3. 需使用者資料目錄 → Environment.GetFolderPath(SpecialFolder.LocalApplicationData)
  4. 需暫存檔 → Path.GetTempPath()
  5. Web 靜態檔 → IWebHostEnvironment.WebRootPath

總結

沒有萬用的「目前路徑」,只有正確的「語境路徑」。建立專案專屬的 IAppPathService,在啟動時一次解析並修正單一檔案/服務/容器環境差異,後續全程依賴注入使用,即可徹底消除路徑相關 Bug。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved