Breaking News

Thursday 26 September 2013

C# File I/O using Read and Write into Text File

C# READING AND WRITING TO TEXT FILES :

the StreamReader and StreamWriter Classes are used for reading from and writing data to text files. these classes inherit from the base class stream , which supports reading and writing bytes into a file stream.

The StreamReader Class :

the StreamReader class also inherit from the abstract base class TextReader that represents a reader for reading series of characters.

some of the commonly used method of the StreamReader Class :


  • Close()  >> it closes the StreamReader object and Stream , and release any system resource associated with the reader.
  • Peek()   >> return the next available character but does not consume it.
  • Read()  >> reads the next character from the input stream.
example :

the following example demonstrates reading a text file named test.txt. the file reads :

using system;
using system.IO;

namespace fileapplication
{
   class program
     {
        static void Main( String[] args )
          {
             try
              {
                 // create an instance of StreamReader to read from a file.
                // the using statement also closed the StreamReader.
                  using( StreamReader sr = new StreamReader ( "C://test.txt"))
                    {
                      string line;
                        // read and display lines from the files until
                        // the end of the file is reached.
                        While (( line = sr.ReadLine()) != null)
                           {
                              Console.WriteLine(line);
                           }
                      }
                  }
    catch ( Exception e )
      {
         // let the user know what went wrong.
         Console.WriteLine(" the file could not be read.."+ e.Message);
      }
Console.ReadKey();
       }
    }
 }

 guess what display when you compile and run the program..

example 2..


using System.IO;

namespace srreamreader_class.cs

{

    class Program

    {
        public void readData()
        {
            FileStream fs = new FileStream("C://myfile/myfile.txt", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            // position the file pointer at the beginning of the file..
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            // read till the end of the file
            string str = sr.ReadLine();
            while (str != null)
            {
                Console.WriteLine("" + str);
                str = sr.ReadLine();
            }
            sr.Close();
            fs.Close();
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.readData();
        }
    }
}


output :



reference link :


The StreamWriter Class :

the StreamWriter class inherits from the abstract from the abstract classes TextWriter represent a writer , which can write a series of a character.

the mos commonly used method of StreamWriter Class are:


  • Close()   >> close the current StreamWriter class and Stream.
  • Flush()  >> clears all buffers for current writer.
  • Write(bool value) >> write the text value to the text string or stream. ( inherited from TextWriter.)
  • Write(char value) >> writes a character to the stream.
  • Write(decimal value) >> write the text representation of decimal value to the text string or stream.
  • Write(double value) >> write the text representation of 8-byte floating point  value to the text string or stream.
  • Write( int value) >> write the text representation of 4-byte integer value to the text string or stream.
  • Write( string value) >> writes a string to the stream.
  • WriteLine() >> write a line to the stream.

the following code demonstrates writing text data into a file using the StreamWriter Class:


using System.IO;
namespace streamwriter_class.cs
{
    class Program
    {
        public void writedata()
        {
            FileStream fs = new FileStream("C://myfile/myfile.txt", FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            // enter a string which is stored in the file myfile.txt
            Console.WriteLine("enter a string..");
            string str = Console.ReadLine();
            //write the string entered by the user in the file myfile.txt
            sw.Write(str);
            // clear all buffer of the current writer
            sw.Flush();
            sw.Close();
            fs.Close();
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
           
            Program p = new Program();
            p.writedata();
        }
    }

}

output :




reference link:




click here to watch an example of StreamWriter Class .

No comments:

Post a Comment

© 2013 Post by repter_x