Reading a file in MVC 6

前端 未结 2 1398
时光说笑
时光说笑 2020-12-19 04:30

I want to access my create.sql file in the main folder of my server. It contains queries to set up my database. I have a problem to access this file at all.

2条回答
  •  失恋的感觉
    2020-12-19 05:26

    And also, instead of injecting IApplicationEnvironment you may use PlatformServices.Default.Application.ApplicationBasePath.

    EDIT: Here's a possible implementation of MapPath/UnmapPath as extensions to PlatformServices:

    removed (see EDIT2)
    

    EDIT2: Slightly modified, IsPathMapped() added as well as some checks to see if path mapping/unmapping is really needed.

    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() return the actual execution path and in .net core 2.0, DEBUG mode it is xxx\bin\Debug\netcoreapp2.0, which, obviously is not what is required. Instead, replace PlatformServices with IHostingEnvironment and use environment.WebRootPath.

提交回复
热议问题