Read a text file from local folder

85,221

Solution 1

Just because you added it to your solution doesn't mean the file gets placed into your output Build directory. If you want to use relative path, make sure your TextFile is copied during build to the output directory. To do this, in solution explorer go to properties of the text file and set Copy to Output Directory to Always or Copy if newer

Then you can use

File.Open("textfile.txt");

Solution 2

you need to use one of the following after the check you have made

 string path = @"\\TextConsole\testfile.txt";
 if (File.Exists(path))
 {
  FileStream fileStream = File.OpenRead(path); // or
  TextReader textReader = File.OpenText(path); // or
  StreamReader sreamReader = new StreamReader(path);
 }

Solution 3

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

  int counter = 0;
  string line;

// Read the file and display it line by line.
System.IO.StreamReader file =  new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

reference http://msdn.microsoft.com/en-us/library/aa287535%28v=vs.71%29.aspx

Solution 4

As Bobby mentioned in a comment, using a simple PathCombine in the current folder worked for me:

string txtPath = Path.Combine(Environment.CurrentDirectory, "testfile.txt")
Share:
85,221
Dabiddo
Author by

Dabiddo

Updated on July 09, 2022

Comments

  • Dabiddo
    Dabiddo almost 2 years

    I want to read a text file from my local directory, I added the text file to my c# solution, so it would get copied at deployment.. but how do i open it? I've been searching but all the examples assume I have a C:\textfile.txt:

    I tried just reading the file

    if (File.Exists("testfile.txt"))
    {
       return true;
    }
    

    That didn't work. Then I tried:

    if (File.Exists(@"\\TextConsole\testfile.txt"))
    {
       return true;
    }
    

    but still wont open it.. any ideas??

  • Stan R.
    Stan R. about 14 years
    it won't find the file, because it doesn't exist in his build directory.
  • Bobby
    Bobby about 14 years
    In my eyes the proper way would be string txtPath = Path.Combine(Environment.CurrentDirectory, "testfile.txt");.
  • Scott Nimrod
    Scott Nimrod over 9 years
    Make sure that "copy to output directory" is set to true in your project properties pane. This will copy the files to the bin directory where the read access will occur.