Number a listing. Assumes fewer than 1000 lines. - CSharp File IO

CSharp examples for File IO:Text File

Description

Number a listing. Assumes fewer than 1000 lines.

Demo Code

using System;//from  w  w  w.  ja va2  s  .c  om
using System.IO;
class NumberIT
{
    public static void Main(string[] args)
    {
        StreamReader InFile = null;
        StreamWriter OutFile = null;

        try
        {
            InFile = File.OpenText("main.cs");
            OutFile = File.CreateText("outfile.txt");

            string line = InFile.ReadLine();
            int ctr = 1;
            while (line != null)
            {
                OutFile.WriteLine("{0}: {1}", ctr.ToString(), line);
                Console.Write("..{0}..", ctr.ToString());
                ctr++;
                line = InFile.ReadLine();
            }
        }
        catch (System.IO.FileNotFoundException)
        {
            Console.WriteLine("Could not find the file {0}", args[0]);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e.Message);
        }
        finally
        {
            if (InFile != null)
            {
                InFile.Close();
                OutFile.Close();
                Console.WriteLine("...Done.");
            }
        }
    }
}
     

Result


Related Tutorials