Get path to App_Data folder in Seed method of EF migration config class
How do you get the path to the App_Data folder in the Seed method of the config class of the first code migrations.
I want to read from a file that was placed in the App_Data folder and the Seed method is run after the update-database command. HttpContext.Current.Server.MapPath is clearly not working because there is no HttpContext at this point.
source to share
@Rusty Divine gave a good answer, however you might find this is better for you:
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");
For example:
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");
This way (using Regx) we make sure that the only replacement can be in the suffix (at the end) of the string AppDomain.CurrentDomain.BaseDirectory
. If the server path contains subfolders named "\ bin \ Debug", they will not be replaced.
This solution is case insensitive, which means that "\ BIN \ debug" will also be replaced.
Also, you don't need to add lines to one line.
System.IO.Path.Combine
will do it for you.
source to share
For what it's worth ... you need to replace the string if you are going to use BaseDirectory in your unit test. But this problem still has the problem that it is using the path of your unit test project, so get tired of that if you try to point files in another project. In this case, you will have to hard-code the path.
AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug","") + "\\App_Data";
source to share