Read files from a Folder present in project

I have a C# project (Windows Console Application). I have created a folder named Data inside project. There are two text files inside folder Data.

How can I read the text files from "Data" folder. I tried below things.

string[] files = File.ReadAllLines(@"Data\Names.txt")

It is thowing error that file not found.

I have checked some Stackoverflow answers posted before and none of then are working for me.

How can I proceed? Thanks!


Solution 1:

below code should work:

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt");
string[] files = File.ReadAllLines(path);

Solution 2:

it depends where is your Data folder

To get the directory where the .exe file is:

AppDomain.CurrentDomain.BaseDirectory

To get the current directory:

Environment.CurrentDirectory

Then you can concatenate your directory path (@"\Data\Names.txt")

Solution 3:

If you need to get all the files in the folder named 'Data', just code it as below

string[] Documents = System.IO.Directory.GetFiles("../../Data/");

Now the 'Documents' consists of array of complete object name of two text files in the 'Data' folder 'Data'.

Solution 4:

I have a C# project (Windows Console Application). I have created a folder named Images inside project. There is one ico file called MyIcon.ico. I accessed MyIcon.ico inside Images folder like below.

this.Icon = new Icon(@"../../Images/MyIcon.ico");

Solution 5:

Copy Always to output directory is set then try the following:

 Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
 String Root = Directory.GetCurrentDirectory();