2015-06-04 36 views
8

我想訪問我的服務器主文件夾中的我的create.sql文件。它包含查詢來設置我的數據庫。我有一個問題來訪問這個文件。在MVC中讀取文件6

1)我不能通過Configuration到達那裏。我只能使用AddJsonFile,AddXmlFileAddIniFile。我想這不是把大的sql文件放入其中的最好辦法。

2)Mvc source on github似乎缺少MapPath。所以沒有可能使用Server.MapPath("~/create.sql")

如何實現這個呢?

+0

'MapPath'是ASP.NET的一部分。 –

+3

您可以使用IApplicationEnvironment服務上的ApplicationBasePath屬性來獲取應用程序的根路徑......好奇,您試圖達到的場景是什麼? –

+0

@KiranChalla It works,wonderful,thank you!如果你願意,請把它寫成答案,我會接受它:)關於你的問題 - 我想在服務器啓動時構建我的數據庫(表,函數等)的結構。 –

回答

15

正如已經注意到並在評論中提到的,ASP.NET VNext(MVC 6)中似乎沒有MapPath。我發現這裏的解決辦法:

http://forums.asp.net/t/2005166.aspx?HostingEnvironment+Equivalent+For+MapPath

基本上你需要從IApplicationEnvironment接口,目前被作爲一種服務來實現獲得ApplicationBasePath,以下解決方案如下:

private readonly IApplicationEnvironment _appEnvironment; 

    public HomeController(IApplicationEnvironment appEnvironment) 
    { 
     _appEnvironment = appEnvironment; 
    } 

    public IActionResult Index() 
    { 
     var rootPath = _appEnvironment.ApplicationBasePath; 
     return View(); 
    } 
4

並且也代替注射IApplicationEnvironment您可以使用PlatformServices.Default.Application.ApplicationBasePath

EDIT:這裏的一個可能的實現的MapPath/UnmapPath作爲擴展PlatformServices

removed (see EDIT2) 

EDIT2:稍加修改,IsPathMapped()加入以及一些檢查是否路徑映射/取消映射是真的需要。

public static class PlatformServicesExtensions 
{ 
    public static string MapPath(this PlatformServices services, string path) 
    { 
     var result = path ?? string.Empty; 
     if (services.IsPathMapped(path) == false) 
     { 
      var wwwroot = services.WwwRoot(); 
      if (result.StartsWith("~", StringComparison.Ordinal)) 
      { 
       result = result.Substring(1); 
      } 
      if (result.StartsWith("/", StringComparison.Ordinal)) 
      { 
       result = result.Substring(1); 
      } 
      result = Path.Combine(wwwroot, result.Replace('/', '\\')); 
     } 

     return result; 
    } 

    public static string UnmapPath(this PlatformServices services, string path) 
    { 
     var result = path ?? string.Empty; 
     if (services.IsPathMapped(path)) 
     { 
      var wwwroot = services.WwwRoot(); 
      result = result.Remove(0, wwwroot.Length); 
      result = result.Replace('\\', '/'); 

      var prefix = (result.StartsWith("/", StringComparison.Ordinal) ? "~" : "~/"); 
      result = prefix + result; 
     } 

     return result; 
    } 

    public static bool IsPathMapped(this PlatformServices services, string path) 
    { 
     var result = path ?? string.Empty; 
     return result.StartsWith(services.Application.ApplicationBasePath, 
      StringComparison.Ordinal); 
    } 

    public static string WwwRoot(this PlatformServices services) 
    { 
     // todo: take it from project.json!!! 
     var result = Path.Combine(services.Application.ApplicationBasePath, "wwwroot"); 
     return result; 
    } 
} 

EDIT3:PlatformServices.WwwRoot()回報的實際執行路徑,並在.NET 2.0的核心,DEBUG模式下,它是XXX \斌\調試\ netcoreapp2.0,顯然這是不是需要什麼。而應將PlatformServices替換爲IHostingEnvironment並使用environment.WebRootPath