Using File.ReadAllText in a Dependency Injected Project

I have a project that's used as a utility and another project that is the main source of my application. The utility project needs to be able to read a JSON file on disk so I use absolute paths and have it look for the file in a subdirectory @''folder/folder2/file.json". This works fine in unit tests as the test project looks for the files in its bin directory where the JSON files and their subdirectories are placed after build. However when I try to use the class from the utility project in the main project via dependency injection it ends up looking in the project directory of the main project and not it's build folder (bin/debug) where the JSON files are.
I registered the utility class via Services.AddSingleton<IUtilityClass, UtilityClass>(). Is there anything that i should be doing differently here? I'm struggling to figure out why it's looking in the wrong directory
7 Replies
mtreit
mtreit2w ago
The "current working directory" cwd (sometimes also called "present working directory" pwd) is the path from which the executable was invoked and that's where relative paths (you said absolute path but I think you meant relative?) are rooted from. So this code:
var currentFolder = Path.GetFullPath(".");
Console.WriteLine(currentFolder);
var currentFolder = Path.GetFullPath(".");
Console.WriteLine(currentFolder);
Will print different values depending on where you invoke the exe from.
LiquidPlazmid
LiquidPlazmidOP2w ago
Yes sorry I meant relative. And the different paths I expected. I'm just confused why it's not looking in the build directory
mtreit
mtreit2w ago
You can use AppContext.BaseDirectory; to get the folder where the executable is and build your path from that.
Sehra
Sehra2w ago
the default is project dir as working dir, you can change it in project debug settings, try with $(OutDir)
LiquidPlazmid
LiquidPlazmidOP2w ago
It's looking for the files in the main projects working directory. I know that much. The files are present in the utility projects working directory and the main projects build folder
mtreit
mtreit2w ago
Just do something like
var jsonPath = Path.Combine(AppContext.BaseDirectory, "folder/folder2/file.json");
var jsonPath = Path.Combine(AppContext.BaseDirectory, "folder/folder2/file.json");
It's best to explicitly resolve the root path where your program lives than to rely on the current working directory. Since as you saw it can change depending on how the program is invoked.
LiquidPlazmid
LiquidPlazmidOP2w ago
This fixed everything thanks!

Did you find this page helpful?