Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read files from a Folder present in project

Tags:

c#

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!

like image 280
skjcyber Avatar asked Dec 07 '12 11:12

skjcyber


People also ask

How do I read a project file?

Answers. You will likely want to have the contents of the Data folder copied to your output folder, which will allow you to access the file using the relative path name: Data\myTextFile. txt. To have the file copied to your output folder, select that file, change its' type to Content and select Copy if newer.

What method is used to read the content of a folder?

readdir() Method. The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory.

How do I read a file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);


2 Answers

below code should work:

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt"); string[] files = File.ReadAllLines(path); 
like image 101
Morbia Avatar answered Oct 06 '22 00:10

Morbia


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")

like image 21
Massimiliano Peluso Avatar answered Oct 06 '22 01:10

Massimiliano Peluso