在MVC 6中读取文件

时间:2015-06-04 23:49:03

标签: c# asp.net-core asp.net-core-mvc

我想访问服务器主文件夹中的create.sql文件。它包含用于设置数据库的查询。我有一个问题就是访问这个文件。

1)我无法真正通过Configuration到达那里。我只能使用AddJsonFileAddXmlFileAddIniFile。而且我认为将一个大的sql文件放入其中的任何一个都不是最好的主意。

2)Mvc source on github似乎缺少MapPath。因此无法使用Server.MapPath("~/create.sql")

如何实现这一目标呢?

2 个答案:

答案 0 :(得分:16)

正如已经注意到并在评论中提到的,似乎ASP.NET VNext(MVC 6)中没有MapPath。我在这里找到了解决方法:

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

基本上,您需要从ApplicationBasePath接口获取IApplicationEnvironment,该接口当前是作为服务实现的,遵循以下解决方案:

    private readonly IApplicationEnvironment _appEnvironment;

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

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

答案 1 :(得分:5)

而且,您可以使用IApplicationEnvironment而不是注入PlatformServices.Default.Application.ApplicationBasePath

编辑:以下是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 core 2.0中,DEBUG模式是xxx \ bin \ Debug \ netcoreapp2.0,这显然不是什么需要。相反,请将PlatformServices替换为IHostingEnvironment并使用environment.WebRootPath