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

谁说胖子不能爱 提交于 2019-12-01 03:30:28

I use this function to map paths inside the Seed method, not very clean but it works:

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")))
Aristos

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!