Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file in project's root directory?

Tags:

c#

wpf

I want to read the first line of a text file that I added to the root directory of my project. Meaning, my solution explorer is showing the .txt file along side my .cs files in my project.

So, I tried to do:

TextReader tr = new StreamReader(@"myfile.txt"); string myText = tr.ReadLine(); 

But this doesn't work since it's referring to the Bin Folder and my file isn't in there... How can I make this work? :/

Thanks

like image 308
Shai UI Avatar asked Jun 20 '11 19:06

Shai UI


People also ask

What is root directory of a project folder?

Create New Project: Choose Project Directory The project root is the folder which is the parent for all the project sources. By default, all subfolders in this folder are treated as sources and their files are involved in indexing, searching, parsing, code completion, and so on.

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

From Solution Explorer, right click on myfile.txt and choose "Properties"

From there, set the Build Action to content and Copy to Output Directory to either Copy always or Copy if newer

enter image description here

like image 127
dance2die Avatar answered Oct 03 '22 05:10

dance2die


You can use the following to get the root directory of a website project:

String FilePath; FilePath = Server.MapPath("/MyWebSite"); 

Or you can get the base directory like so:

AppDomain.CurrentDomain.BaseDirectory 
like image 29
Mangesh Pimpalkar Avatar answered Oct 03 '22 05:10

Mangesh Pimpalkar