標籤:.exe 執行檔案 environ 搜尋引擎 exe 上下 process 環境 http
這兩個計劃寫一個小類庫,需要在不同項目下任意調用。該類庫需要對磁碟檔案進行讀寫,所以就需要擷取程式執行的磁碟路徑,就簡單的對擷取磁碟路徑的方法進行研究。
藉助搜尋引擎,我從網上搜羅來多種方法,都可以直接或間接的擷取到應用程式執行的根目錄。大概總結一下,一共有以下 11 種:
Server.MapPath("~") //使用 HTTP 上下文中的 Server 對象來擷取Web網站的根目錄 System.AppDomain.CurrentDomain.BaseDirectory //使用應用程式定義域對象擷取當前線程的應用程式定義域的基準目錄 System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase //使用應用程式定義域對象擷取當前線程的應用程式定義域的配置資訊中的應用程式目錄 System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName //擷取當前進程的主模組的檔案名稱(全路徑。由該檔案路徑可以得到程式集所在的目錄) System.Environment.CurrentDirectory //擷取應用程式環境的目前的目錄 System.IO.Directory.GetCurrentDirectory() //使用靜態類 Directory 下的 GetCurrentDirectory 方法擷取當前程式的路徑 System.Reflection.Assembly.GetCallingAssembly().Location //擷取調用該方法的方法所在的程式集,並擷取該組件檔路徑(由該檔案路徑可以得到程式集所在的目錄) System.Reflection.Assembly.GetEntryAssembly().Location //擷取包含該應用程式進入點的程式集(可執行檔),並擷取該組件檔的路徑(由該檔案路徑可以得到程式集所在的目錄) System.Reflection.Assembly.GetExecutingAssembly().Location //擷取執行該方法的程式集,並擷取該程式集的檔案路徑(由該檔案路徑可以得到程式集所在的目錄) System.Windows.Forms.Application.StartupPath //擷取啟動應用程式的可執行檔所在的目錄 System.Windows.Forms.Application.ExecutablePath //擷取啟動應用程式的可執行檔的路徑(由該檔案路徑可以得到應用程式所在的目錄)
擷取應用程式根目錄實體路徑(Web and Windows)