2009-01-22 18 views
13

我想獲得的文件夾路徑在我的網站的根並將其保存到一個類的屬性,當我控制器構造函數被調用:如何從ASP.NET MVC中的控制器構造函數中找到文件夾的路徑?

public TestController:Controller{ 
    string temp; 

    public TestController(){ 
     temp = ""; 
     } 

    } 

我曾嘗試以下:

temp = Server.MapPath("~/TheFolder/"); // Server is null - error. 
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error. 

有任何想法嗎?

回答

25

AppDomain.CurrentDomain.BaseDirectory將爲您提供站點的根目錄。所以:

temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder"); 

(更新感謝馬克Gravell的評論)

+0

Path.Combine將;-p – 2009-01-22 08:34:02

+0

更好這個返回temp文件夾目錄,可能意味着完全錯誤的文件夾。 – 2013-12-30 11:37:34

0

嘗試通過ControllerContext去。請原諒我的語法,但它應該是這樣的:

base.[Controller?]Context.HttpContext.Server.MapPath(); 

如果服務器是仍然空在這種情況下,你運行一個Web請求的外部(即在一個測試。)?

7

實際上在構造函數期間是否需要這條路徑?如果在主頁面週期開始之前您不需要它,請考慮推遲它 - 僅使用常規屬性;像

public string BasePath { 
    get { return Server.MapPath("~/TheFolder/"); } 
} 

然後,當在頁面循環中使用它時,應該沒問題。你可以緩存,如果你真的想,但我不想象這將是一個瓶頸:

private string basePath; 
public string BasePath { 
    get { 
     if(basePath == null) basePath = Server.MapPath("~/TheFolder/"); 
     return basePath; 
    } 
} 
相關問題