1

I have two projects .NET Web API 2 projects, MyProject and MyProject.Tests. MyProject has a settings.json file which I use to store database credentials. I used a custom external settings file because the database credentials includes a username and password that shouldn't be bundled in with other settings and are user-specific.

I wrote a ConfigManager() class with a GetDbConnectionString() method that reads the DB credentials from an external file and generates a connection string. It uses a relative path to the config file that lives in the project directory. This works fine during normal execution, because the path is relative to MyProject. However when running units tests, all relative paths are relative to MyProject.Tests, and fail to find the proper file. I can use an absolute path, but I would prefer for all settings files to be bundled in the project directory.

Is there a way I can have the unit tests fine the settings file properly without duplicating it in the unit test project and without using absolute paths>

UpQuark
  • 791
  • 1
  • 11
  • 35
  • Why don't you use "copy as a Link"? it will solve your problem without the maintenance issue of copy.... – Old Fox Sep 16 '15 at 16:45

1 Answers1

-1

You may want to use Directory.GetCurrentDirectory() or System.Reflection.Assembly.GetExecutingAssembly().Location to get to the path.

Directory.GetCurrentDirectory() will give you the current folder (which is more of a context, as you can create a shortcut and pass a completely different folder as your current directory than the one where your exe is present).

System.Reflection.Assembly.GetExecutingAssembly().Location will give you the path of the dll (or exe depending on compilation option).

System.Reflection.Assembly.GetAssembly(typeof(ConfigManager)).Location; should give what you are looking for.

Refer to suggestions in How do I get the path of the assembly the code is in?

Community
  • 1
  • 1
Adarsha
  • 2,267
  • 22
  • 29
  • Unfortunately this gives me a directory, but it's the MyProject.tests directory. MyProject.Tests is calling a method in MyProject that calls the config manager, but that method still gets MyProject.Tests as the directory from these methods. – UpQuark Sep 15 '15 at 17:21