[Tips][C#] 如何取得 Windows / ASP .Net 程式 Base Directory

如何取得 Windows / ASP .Net 程式 Base Directory

前言

 

最近客戶寫了一個類別庫(Class Library)提供筆者使用,而該類別庫需使用到相同路徑下的一個外部檔案作為資料處理時參考的依據。由於客戶是使用Windows Form來驗證此類別庫,因此在設定該外部檔案位置時是使用System.AppDomain.CurrentDomain.BaseDirectory方式來取得路徑資訊;但就在筆者將該類別庫加入ASP .Net MVC專案來使用時,卻拋出無法取得該外部檔案的錯誤訊息,此時才發現原來不同型態專案的Base Directory取得方式是不相同的,因此可以透過以下方式來解決此問題。

 

 

實作

 

可以透過以下代碼來取得 Windows / ASP .Net 應用程式 Base Directory。若在Windows Form / Console專案中,AppDomain.CurrentDomain.RelativeSearchPath會為Null值,因此就可以透過 BaseDirectory 獲得所需路徑;反之若是ASP .Net 專案則使用AppDomain.CurrentDomain.RelativeSearchPath即可。

 


{
    var appDomain = System.AppDomain.CurrentDomain;
    var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
    return basePath;
}

 

簡單地驗證一下,分別在Console及ASP .Net MVC 專案中執行以下代碼。

 


var baseDirectory = ClassLibrary.Utility.GetBasePath();
// get file location by base directory
var fileLocation = Path.Combine(baseDirectory, "boo.txt");

 

結果如下

Call By Console Project (路徑正確)

 

image

 

Call By ASP .Net MVC Project (路徑正確)

 

image

 

 

參考資訊

 

http://stackoverflow.com/questions/15401925/path-to-file-in-class-library


希望此篇文章可以幫助到需要的人

若內容有誤或有其他建議請不吝留言給筆者喔 !