C# 獲取程式路徑的幾種方法及其區別【WPF】

小林野夫發表於2024-03-29

遇到的問題

但最近發現一個問題:如果程式是由使用者透過exe檔案直接開啟的,獲取同目錄下配置檔案不會有問題;但如果程式是由第三方應用啟動的,透過不同方式獲取的“當前目錄”會有不同。以下是常用的記住獲取當前目的的方法:

System.Environment.CurrentDirectory: 獲取當前程式集或者宿主的所在當前目錄。

System.IO.Directory.GetCurrentDirectory(): 獲取當前程式集或者宿主的所在當前目錄。

System.AppDomain.CurrentDomain.BaseDirectory:獲取當前程式集的所在當前目錄。

System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:獲取當前程式集的所在當前目錄。

在window10、window11透過.msix和直接用.exe|.msi 安裝包安裝的軟體,獲取的“當前目錄”會有不同。

解決方案

透過.msix安裝包,安裝的軟體獲取的“當前目錄”

System.Environment.CurrentDirectory

System.IO.Directory.GetCurrentDirectory()

System.AppDomain.CurrentDomain.BaseDirectory(這個是最準確)

對於打包成.msix 程式而言,用這個能準確的讀取設定我Content的資源。

例如讀取 音訊檔案。

System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase


相關文章