Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从EF迁移脚本中查找目录路径的最佳方法是什么?_C#_.net_Entity Framework_Entity Framework Migrations - Fatal编程技术网

C# 从EF迁移脚本中查找目录路径的最佳方法是什么?

C# 从EF迁移脚本中查找目录路径的最佳方法是什么?,c#,.net,entity-framework,entity-framework-migrations,C#,.net,Entity Framework,Entity Framework Migrations,我在项目中使用实体框架代码优先迁移。其中一种迁移通过从项目目录中的csv文件中读取数据来填充数据库表。项目结构如下所示: - Soulution - Project - Migrations - CSVFolder - file1.csv - file2.csv - Migration1.cs - Migration2.cs 在我的Up() public override void Up() {

我在项目中使用实体框架代码优先迁移。其中一种迁移通过从项目目录中的
csv
文件中读取数据来填充数据库表。项目结构如下所示:

- Soulution
    - Project
      - Migrations
        - CSVFolder
          - file1.csv
          - file2.csv
      - Migration1.cs
      - Migration2.cs
在我的
Up()

public override void Up()
{
    var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + "/Migrations/CSVFolder/";   // For some reason, Path.Combine() doesn't work for me here so I manually concatenate the strings.
    var templateFiles = Directory.GetFiles(migrationsDir, "*.csv");

    foreach (var filename in templateFiles)
    {
        Sql();  // SQL Insert statement here.
    }
}
这在我的开发机器上运行得很好,但当我使用Octopus将其部署到测试服务器时,我得到一个path not found异常

找不到路径的一部分 'C:\Octopus\Applications\Test\Solution\1.1-alpha21\Migrations\CSVFolder'

我检查了“drop”文件夹,那里的输出包括
Migrations>CSVFolder


我尝试了几种不同的方法来获取文件夹的路径,但它们要么在本地工作,要么在服务器上工作。获取在本地和服务器上都有效的路径的最佳方法是什么?

您必须正确设置路径
AppDomain.CurrentDomain.BaseDirectory
将在测试测试运行程序目录时返回,并在应用程序模式下获得..\Bin\Debug等。在到达所需位置(CSVFolder)之前,您必须检查有多少目录,然后替换路径或更改路径,例如:

var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + "../../Migrations/CSVFolder/";   // For some reason, Path.Combine() doesn't work for me here so I manually concatenate the strings.
你已经注意到,你想要做的事情并不容易,所以你可以忘记这个方法,这就是诀窍。最好的方法是将cvs文件附加到程序集资源!在迁移过程中,您可以按如下方式访问它们:

在Up()中

这种方法将保证Sql或Cvs文件在运行时始终附加/加载到程序集。

这对我很有用

AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory

“你必须检查你有多少个目录,直到你能到达所需的位置”——这正是问题所在。老实说,我真的不想将它们作为资源嵌入,但这似乎是确保在这两种情况下都正确使用它们的最佳方法。现在,我使用
Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory,“CSVFolder”)[0]
解决了这个问题。这是可行的,但假设不会有多个名为“CSVFolder”的目录。
AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory