How to: Read a Text File
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How to: Read a Text File 

The following code example demonstrates how to open and read a text file one line at a time. This is accomplished with the StreamReader class defined within the System.IO namespace. An instance of this class is used to open a text file and then the System.IO.StreamReader.ReadLine method is used to retrieve each line.

This code can be used with any file named textfile.txt that contains text or with the file generated in How to: Write a Text File.

Example

// text_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";
   try 
   {
      Console::WriteLine("trying to open file {0}...", fileName);
      StreamReader^ din = File::OpenText(fileName);

      String^ str;
      int count = 0;
      while ((str = din->ReadLine()) != nullptr) 
      {
         count++;
         Console::WriteLine("line {0}: {1}", count, str );
      }
   }
   catch (Exception^ e)
   {
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("file '{0}' not found", fileName);
      else
         Console::WriteLine("problem reading file '{0}'", fileName);
   }

   return 0;
}

See Also

Show:
© 2016 Microsoft