Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streamreader to a relative filepath

I was wondering, if anyone could tell me how to point a StreamReader to a file inside the current working directory of the program.

E.g.: say I have program Prog saved in the directory "C:\ProgDir\". I commit "\ProgDir" to a shared folder. Inside ProgDir is another directory containing files I'd like to import into Prog (e.g. "\ProgDir\TestDir\TestFile.txt") I'd like to make it so that the StreamReader could read those TestFiles, even when the path to the directory has changed;

(E.G., on my computer, the path to the Testfiles is

C:\ProgDir\TestDir\TestFile.txt

but on the other person's computer, the directory is

C:\dev_code\ProgDir\TestDir\TestFile.txt

).

How would I get a StreamReader to be ale to read from TestFile.txt on the other person's computer? (to clarify, the filenames do not change, the only change is the path ProgDir)

I tried the following:

string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
FileInfo file = new FileInfo("TestFile.txt");

string fullDirectory = directory.FullName;
string fullFile = file.FullName;

StreamReader sr = new StreamReader(@fullDirectory + fullFile);

( pulled this from : Getting path relative to the current working directory?)

But I'm getting "TestFile does not exist in the current context". Anyone have any idea as to how I should approach this?

Thank you.

like image 670
gfppaste Avatar asked May 16 '12 17:05

gfppaste


People also ask

How to give path to StreamReader in c#?

CurrentDirectory; DirectoryInfo directory = new DirectoryInfo(currentDir); FileInfo file = new FileInfo("TestFile. txt"); string fullDirectory = directory. FullName; string fullFile = file. FullName; StreamReader sr = new StreamReader(@fullDirectory + fullFile);

How do you make a path relative?

Relative path Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory.

What is StreamReader and StreamWriter in C#?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.


1 Answers

Is the Folder "TestDir" always in the executable directory? if so, try this

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

    string file = dir + @"\TestDir\TestFile.txt";

This will give you the path of the exe plus the folder inside it and the textfile

like image 136
hjgraca Avatar answered Nov 07 '22 20:11

hjgraca