[英]How to read a file content from EF Configuration.cs file?
I am using EF 6 Code-base migration. 我正在使用EF 6代码库迁移。 I want to read the file from Configuration.cs Seed() method to insert as default data. 我想从Configuration.cs Seed()方法中读取文件以作为默认数据插入。 I am using HostingEnvironment.MapPath() as below: 我正在使用HostingEnvironment.MapPath()如下:
string _homeContent = System.IO.File.ReadAllText( HostingEnvironment.MapPath(@"~/Data/DefaultContents/Home.html"));
But HostingEnvironment.MapPath return null value when I run the Update-database command from Package-Management Console . 但是,当我从Package-Management Console运行Update-database命令时,HostingEnvironment.MapPath返回null值。
Running Seed method. 运行种子方法。
System.ArgumentNullException: Value cannot be null. System.ArgumentNullException:值不能为null。
Parameter name: path at System.IO.File.ReadAllText(String path) 参数名称:System.IO.File.ReadAllText的路径(字符串路径)
Kindly advise how to read the physical file from Configuration.cs Seed() method. 请告知如何从Configuration.cs Seed()方法读取物理文件。
May I answer by myself. 我可以自己回答。
Server.MapPath and HostingEnvironment.MapPath is not available in this time because HttpContext object is not ready yet. 由于HttpContext对象尚未准备好,所以Server.MapPath和HostingEnvironment.MapPath暂时不可用。
AppDomain.CurrentDomain.BaseDirectory return "..\\your project directory\\bin" AppDomain.CurrentDomain.BaseDirectory返回“ .. \\您的项目目录\\ bin”
Eg C:\\YourSolutionDirectory\\YourProjectDirectory\\bin 例如C:\\ YourSolutionDirectory \\ YourProjectDirectory \\ bin
But we need to go up from " bin " folder, so that using Path.Combine() method and get exact file path. 但是我们需要从“ bin ”文件夹上移 ,以便使用Path.Combine()方法并获取确切的文件路径。
string homeFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", @"Data\DefaultContents\Home.html");
Result: C:\\YourSolutionDirectory\\YourProjectDirectory\\Data\\DefaultContents\\Home.html 结果:C:\\ YourSolutionDirectory \\ YourProjectDirectory \\ Data \\ DefaultContents \\ Home.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.