Elliot Blackburn
Elliot Blackburn

Reputation: 4174

Referencing a file not in the project solution c#

Struggling with a small part to a recent assignment, we've been asked to provide only the .cs file during the hand in process of our assignment, however it also asks us to reference a .txt file. Without setting the exact path to my file (ie: c:\users\username\documents etc).

The program is console based as this is just an algorithm and structure class, but I'm still a little miffed on how to reference without having the reference be static, or the txt document being added to a solution.

I've considered asking for the directory path input at the start of the program, but I just wondered if there was a better way of doing it.

Upvotes: 0

Views: 107

Answers (2)

Paolo
Paolo

Reputation: 22646

You've pretty much covered the options. If you can only provide that cs file then you can only:

  • Hard-code the location in the file as an absolute path - e.g. c:\testfile.txt
  • Hard-code the location as a relative path - e.g. ..\testfile.txt
  • Get the location as a command line argument
  • Make the console program interactive and prompt for the location after it starts
  • Get the location from an environment variable

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151730

Just read the file from the application's directory, for example using this:

using (var reader = new StreamReader("myfile.txt"))

Upvotes: 0

Related Questions