JARRRRG
JARRRRG

Reputation: 926

Visual studio project directory issue

I'm writing to a text folder which is in a folder within my project but I can't seem to get to it without writing the absolute complete path as it is on my computer which is fine on this computer but when I want to take it elsewhere I can't have that as the drives are different etc.

Here is a screenshot of the lines I'm using to get it to post to the directory on the right.

The file I'm trying to access is in a folder called AdminAccount and is called User.txt. it works fine as you can see from the commented directory link as a direct path but when I try with the directory string in use it does not work.

https://i.sstatic.net/1KemD.png

Any help how to get around this? I tried all sorts, I tried doing

private string[] getLines = System.IO.File.ReadAllLines(@"\AdminAccount\User.txt");
private string[] getLines = System.IO.File.ReadAllLines(@"..\AdminAccount\User.txt");

No joy.

Upvotes: 1

Views: 137

Answers (2)

Kurubaran
Kurubaran

Reputation: 8892

You can use,

string rootPath = Environment.CurrentDirectory;
string filePath = Path.Combine(rootPath,@"..\..\AdminAccount\User.txt");
private string[] getLines = System.IO.File.ReadAllLines(@filePath);

..\ is used to access a top level folder in the hierarchy. you can keep on adding ..\ to move up in the hierarchy.

Ex:

string path1 = @"C:\Users\Documents\Visual Studio 2010\Projects\Test\Test\bin\Debug"
string newPath = Path.Combine(path1, @"..\..\AdminAccount\User.txt");

new path would return C:\Users\Documents\Visual Studio 2010\Projects\Test\Test\AdminAccount\User.txt

Upvotes: 1

Damith
Damith

Reputation: 63105

You just have to set the property "Copy to Output Directory" of the "User.txt" file to "Copy allways" or "Copy if newer".

Now you can read the lines as below

string[] getLines = File.ReadAllLines(
                 Path.Combine(Application.StartupPath, "AdminAccount", "User.txt"));

Upvotes: 0

Related Questions