Manipulating a string read as a line from a file : Ascii String Read Write : File Stream C# Source Code


Custom Search

C# Source Code » File Stream » Ascii String Read Write »

 

Manipulating a string read as a line from a file








    

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  Builder.cs -- Demonstrates manipulating a string read as a line from a file
//                Compile this program with the following command line:
//                    C:>csc Builder.cs
//
namespace nsBuilder
{
    using System;
    using System.Text;
    using System.IO;
    public class Builder
    {
        static public int Main ()
        {
// Create a stream object and open the input file
            FileStream istream;
            try
            {
                istream = new FileStream ("sample.txt", FileMode.Open, FileAccess.Read);
            }
            catch (Exception)
            {
                Console.WriteLine ("Could not open sample.txt for reading");
                return (-1);
            }
// Associate a reader with the stream
            StreamReader reader = new StreamReader (istream);
// Declare a new StringBuilder
            StringBuilder strb = new StringBuilder ();
// Counter for the lines
            int Lines = 0;
            while (reader.Peek() > 0)
            {
                ++Lines;
// Clear out the string builder
                strb.Length = 0;
// Read a line from the file
                string str = reader.ReadLine();
// Split the line into words
                string [] Data = str.Split (new char [] {' '});
// Build the output line to show line, word and character count
                strb.AppendFormat ("Line {0} contains {1} words and {2} characters:\r\n{3}", Lines, Data.Length, str.Length, str);
// Write the string to the console
                Console.WriteLine (strb.ToString ());
            }
            istream.Close ();
            return (0);
        }
    }
}

//File: sample.txt
/*
The quick red fox jumps over the lazy brown dog.
Now is the time for all good men to come to the aid of their Teletype.
Peter Piper picked a peck of peppered pickles.


*/

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo File Stream
» Ascii String Read Write