简体   繁体   English

实体框架 - 如何在种子方法中获取相对文件路径

[英]Entity Framework - How to get relative file path in seed method

Why is filePath null? 为什么filePath为null? Any ideas on how to get the relative filePath? 有关如何获取相对filePath的任何想法?

internal sealed class Configuration : DbMigrationsConfiguration<MvcProject.Models.FileDb>
{
    public Configuration()
    {
        // code here is not relevant to question
    }
    protected override void Seed(MvcProject.Models.FileDb context)
    {    
        string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/File.txt");

        // read File.txt using filePath and update the database
    }
}

I have the above code in Configuration.cs file in Migrations folder created when entity framework is set up on an ASP .NET MVC project 我在ASP .NET MVC项目上设置实体框架时创建的Migrations文件夹中的Configuration.cs文件中有上述代码

When I run "Update-Database -Verbose" in Package Manager Console I get an error that filePath is null. 当我在包管理器控制台中运行“Update-Database -Verbose”时,我收到一个错误,即filePath为null。

If I manually set filePath with an absolute URL to the file: 如果我手动设置filePath与文件的绝对URL:

string filePath = "C:/Users/User1/My Documents/Visual Studio 2012/Projects/MvcProject/Content/File.txt";

Everything works fine. 一切正常。

Obviously the goal is to have a relative path to enable work with different developers on different setups. 显然,目标是建立一个相对路径,以便在不同的设置上与不同的开发人员一起工作。

Truth be told all I need is the file - not necessarily the path. 真相被告知所有我需要的是文件 - 不一定是路径。 Any help will be appreciated. 任何帮助将不胜感激。

I use this function to map paths inside the Seed method, not very clean but it works: 我用这个函数来映射Seed方法里面的路径,不是很干净但是它有效:

private string MapPath(string seedFile)
{
    if(HttpContext.Current!=null)
        return HostingEnvironment.MapPath(seedFile);

    var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; //was AbsolutePath but didn't work with spaces according to comments
    var directoryName = Path.GetDirectoryName(absolutePath);
    var path = Path.Combine(directoryName, ".." + seedFile.TrimStart('~').Replace('/','\\'));

    return path;
}

then just call it using: 然后使用以下方法调用它:

   using (var streamReader = new StreamReader(MapPath("~/Data/MyFile.csv")))

As I say , I belive that you call it from a page and the System.Web.HttpContext.Current is null, because MapPath function never return null with a not null input - so you get an exception there. 正如我所说的,我相信你从一个页面调用它并且System.Web.HttpContext.Current为null,因为MapPath函数永远不会返回带有非null输入的null - 所以你在那里得到一个例外。

Try that alternative: 尝试替代方案:

string filePath = HttpRuntime.AppDomainAppPath + "/Content/File.txt";

or 要么

string filePath = HostingEnvironment.MapPath("~/Content/File.txt");

Related question: How to access the HttpServerUtility.MapPath method in a Thread or Timer? 相关问题: 如何在线程或计时器中访问HttpServerUtility.MapPath方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM