Asp.net mvc 4 获取EF迁移配置类种子方法中App_数据文件夹的路径

Asp.net mvc 4 获取EF迁移配置类种子方法中App_数据文件夹的路径,asp.net-mvc-4,ef-code-first,entity-framework-5,entity-framework-migrations,Asp.net Mvc 4,Ef Code First,Entity Framework 5,Entity Framework Migrations,如何在代码优先迁移的配置类的Seed方法中获取App_数据文件夹的路径 我想从我放在App_Data文件夹中的文件中读取,种子方法在updatedatabase命令之后运行。HttpContext.Current.Server.MapPath显然不起作用,因为此时没有HttpContext。以下是一种快速而肮脏的入门方法: var myPath = AppDomain.CurrentDomain.BaseDirectory; //to quickly show the path, either

如何在代码优先迁移的配置类的Seed方法中获取App_数据文件夹的路径


我想从我放在App_Data文件夹中的文件中读取,种子方法在updatedatabase命令之后运行。HttpContext.Current.Server.MapPath显然不起作用,因为此时没有HttpContext。

以下是一种快速而肮脏的入门方法:

var myPath = AppDomain.CurrentDomain.BaseDirectory;
//to quickly show the path, either attach another debugger or just throw an exception
throw new Exception(myPath);

我让它与以下东西一起工作:
string MyPath=AppDomain.CurrentDomain.BaseDirectory+“/../App\u Data”


因为
AppDomain.CurrentDomain.BaseDirectory
以“/bin”目录结尾。

因为它的价值。。。如果要在单元测试中使用BaseDirectory,则需要进行字符串替换。但是,它仍然存在一个问题,即它使用单元测试项目的路径,因此如果您试图指向另一个项目中的文件,请对此感到厌倦。在这种情况下,必须对路径进行硬编码

AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug","") + "\\App_Data";

@Rusty Divine给出了一个很好的答案,但也许你会发现这对你更有利:

System.IO.Path.Combine( System.Text.RegularExpressions.Regex.Replace(AppDomain.CurrentDomain.BaseDirectory, @"\\bin\\Debug$", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase) ,   RELATIVE_PATH,  "FILENAME.EXE");
例如:

System.IO.Path.Combine( System.Text.RegularExpressions.Regex.Replace(AppDomain.CurrentDomain.BaseDirectory, @"\\bin$", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase) ,  "App_Data\\Init",   "fileName.txt");
通过这种方式(使用Regx),我们确保唯一可以替换的是
AppDomain.CurrentDomain.BaseDirectory
字符串的后缀(在末尾)。如果在名为“\bin\Debug”的服务器路径中有子文件夹,则不会替换它们

此解决方案不区分大小写,表示“\BIN\debug”也将被替换

此外,您不需要将字符串附加到一个字符串中。
System.IO.Path.Combine
将为您完成此操作。

可能仅在产品中。调试时在IDE中,
AppDomain.CurrentDomain.BaseDirectory
指向项目根目录。