Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

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

Why is filePath null? Any ideas on how to get the relative 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

When I run "Update-Database -Verbose" in Package Manager Console I get an error that filePath is null.

If I manually set filePath with an absolute URL to the file:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...