Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to find directory path from an EF migration script?

I'm using Entity Framework code first migrations in my project. One of these migrations populates a database table by reading in data from csv files located in a directory in the project. The project structure looks like this:

- Soulution
    - Project
      - Migrations
        - CSVFolder
          - file1.csv
          - file2.csv
      - Migration1.cs
      - Migration2.cs

In my Up() method, I get these files like so:

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.
    }
}

This runs fine on my dev machine but when I deploy this to the test server with Octopus, I get a path not found exception

Could not find a part of the path 'C:\Octopus\Applications\Test\Solution\1.1-alpha21\Migrations\CSVFolder'.

I've checked the 'drop' folder and the output there includes Migrations > CSVFolder.

I've tried a few different ways to get the path to the folder but they work either locally or on the server. What's the best way to get the path that will work both locally and on the server?

like image 871
reggaemahn Avatar asked Oct 18 '22 04:10

reggaemahn


1 Answers

You have to set the path correctly! AppDomain.CurrentDomain.BaseDirectory will returns in case of testing the test runner directory and in the application mode you will get ..\Bin\Debug etc. You have to check how many directories you have until you can reach the desired location(CSVFolder) and then replace the path or change it for example :

var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + "../../Migrations/CSVFolder/";   // For some reason, Path.Combine() doesn't work for me here so I manually concatenate the strings.

You have noticed that is not easy what you are trying to do so you can forget this apporach and this is the trick. The best way is just attach the cvs files to the assembly resources! and during the migrations you can access them like the following:

in Up()

var file1 = Properties.Resources.File1;

This approach will guarantee that the Sql or Cvs files will always attached/loaded to the assembly at the runtime.

like image 167
Bassam Alugili Avatar answered Oct 21 '22 02:10

Bassam Alugili