0

My exact file path is as follows. This .txt file is not supposed to be deployed to bin/debug

string str = File.ReadAllText(@"C:\development\slnfolder\projfolder\myfile.txt");

How can I write the code so that I do not have to hard code full path to get to the file

I am trying to avoid hard coding path in the above line of code as follows:

string file = @"myfile.txt";
string str = Path.GetFullPath(file);

but the str ends up being as follows and is not able to find the file.

C:\development\slnfolder\projfolder\bin\debug\myfile.txt

dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200

4 Answers4

2

You can include myfile.txt in your Visual Studio solution and go to its properties and set the Build action to Copy always (or Copy if newer if you want to avoid copying the file if it didn't change since the previous build...).

This way you're going to have the whole file in the target directory (i.e. bin\debug).

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

That's where it should map, because that's where your executable is running from. I'd highly suggest you ensure that the text file is moved to the bin/debug folder (there's a VS option to copy it down in properties) rather than trying to read two levels up. It will be much easier once you end up deploying your app instead of running it from visual studio.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Paths do not relate to the exe directory. They relate to the current directory. – usr Jan 14 '13 at 19:27
  • @usr And since windows users don't really use the command prompt like...ever, in practice they're the same. – Servy Jan 14 '13 at 19:31
  • not if you use the file open dialog. It changes the current directory. Anyway, even if that was not the case I would not agree. Small inexactness like this leads to subtile bugs. The fact that you missed the FOD case shows this. – usr Jan 14 '13 at 20:11
1

If you're using Visual studio, than add the txt file to your project

  • right click on properties
  • set build action to none
  • and set copy to output directory to copy if newer

this will ensure that the txt file is always in the same folder as your executable

1

To avoid hard-coding something, you should:

  • "Soft-code" it (i.e. make it part of your product's configuration). You can use Configuration Settings APIs for that.
  • Take it as a parameter on the command line (read the directory location from one of the args passed to the Main method), or
  • Make a convention as to where it should be located, for example, in the data directory, which is a subdirectory of your current running directory (read from @"..\data\myfile.txt").

You can always define a combination of these methods, for example, use the "by convention" location when the configuration / command line option has not been specified.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523