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

Why is filePath null? Any ideas on how to get 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 the Configuration.cs file in the Migrations folder created when creating the entity structure in an ASP.NET MVC project

When I run "Update-Database -Verbose" in the package manager console, I get an error that filePath is null.

If I manually installed filePath with an absolute URL in the file:

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

Everything works perfectly.

Obviously, the goal is to have a relative path that allows you to work with different developers with different settings.

In truth, all I need is a file - not necessarily a path. Any help would be appreciated.

+6
source share
2 answers

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"))) 
+20
source

As I said, I believe that you are calling it from the page, and System.Web.HttpContext.Current is null because the MapPath function never returns null with a non-zero input - so you get an exception there.

Try this 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 stream or timer?

0
source

Source: https://habr.com/ru/post/943803/


All Articles