Cyrendex
Cyrendex

Reputation: 61

Relative path leading to the wrong file in C#

I have a text file called GameSettings.txt which has the absolute path of:

C:\Users\User\Source\Repos\CLIBattleships\CLIBattleships\General\GameSettings.txt

When I try to get its relative path to prevent issues when the project is running from another computer by doing:

private static StreamReader sr = new StreamReader(@"General\GameSettings.txt");

It returns this path instead:

C:\Users\User\Source\Repos\CLIBattleships\CLIBattleships\bin\Debug\netcoreapp3.1\General\GameSettings.txt

I looked up a few similar questions asked here, and the answers suggested that the directory executable is in is different from the current directory.

The few upvoted answers were:

string filePath = System.IO.Path.GetFullPath("TestFile.txt"); 
StreamReader sr = new StreamReader(filePath);

and

string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

string file = dir + @"\TestDir\TestFile.txt";
// then use file as a parameter for the StreamReader

Both of them lead to the same, wrong (at least contextually wrong) relative path. Please help.

Upvotes: 1

Views: 2320

Answers (1)

Nikola Rasic
Nikola Rasic

Reputation: 75

Building the project compiles your code and copies the files into the bin folder. Building and running in "Debug" preset(default) will output your files into bin/Debug/netcoreapp3.1/ folder. Here is where your .exe lies and where its relative path is situated.

Now, for your specific problem, a dirty way to fix this is to use .. inside relative path. This will get you to the root of current directory. Say you state "../../file.txt" as a path. This will look for the file.txt inside the bin folder. BUT - that is not how you should solve this issue. I just wanted to mention this as it's a useful detail to know and there are situations where you can use this to your advantage.

I suggest adding your file either to project resources or as a plain file. Then, as somebody already mentioned, you can set that file as content and make the visual studio copy its contents to the output folder. That way, the file will be copied to the same directory where the executable lies, and your path to it will literally be just the name of the file.

Using the project resources, however, will not expose the files to the file system.

Upvotes: 2

Related Questions