Read text file - CSharp File IO

CSharp examples for File IO:Text File

Description

Read text file

Demo Code


using System;//from   w  ww.ja v a  2  s .  c  om
using System.IO;

class ListIT
{
    public static void Main(string[] args)
    {
      try
      {

        int ctr=0;

            FileStream f = new FileStream("main.cs", FileMode.Open);
            try
            {
               StreamReader t = new StreamReader(f);
               string line;
               while ((line = t.ReadLine()) != null)
               {
                  ctr++;
                  Console.WriteLine("{0}:  {1}", ctr, line);
               }
               f.Close();
            }
            finally
            {
               f.Close();
            }
     
       }
       catch (System.IO.FileNotFoundException)
       {
               Console.WriteLine ("ListIT could not find the file {0}", args[0]);
       }

       catch (Exception e)
       {
          Console.WriteLine("Exception: {0}\n\n", e);
       }
     }
}

Result


Related Tutorials