SunQuest
 
       C#
  Home arrow C# arrow Page 3 - C# StreamReader and StreamWriter Explained
Iron Speed
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
VeriSign Whitepapers 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

C# StreamReader and StreamWriter Explained
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 10
    2007-02-06

    Table of Contents:
  • C# StreamReader and StreamWriter Explained
  • Using StreamWriter to write to a file
  • Step-by-step through the code example
  • Encoding with the classes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    C# StreamReader and StreamWriter Explained - Step-by-step through the code example


    (Page 3 of 4 )

    The first statement in the try block is familiar, we just instantiate a new FileStream instance of the file aFile.txt with FileMode.Create and read/write access with exclusive access to this file. The next string array contains three string values that are used with the WriteLine() method, as we are going to see shortly.

    We create a StreamWriter instance with the using statement to ensure that the StreamWriter.Close() instance method is called automatically. The constructor overload that we are using for this example accepts only one parameter which is the Stream that's used to interact with the source -- in other words the FileStream instance that is used to write to the file.

    Calling the StreamWriter.Close() instance method explicitly or implicitly through the using statement ensures that the data is written to the associated stream object (which in our example is the fs instance) and calls the Close() method of the associated stream object.

    The first Console.WriteLine() method prints out the value of the instance Property StreamWriter.BaseStream, which returns the stream that's associated with the StreamWriter instance, a FileStream instance. The second Console.WriteLine() method prints out the value of the instance Property StreamWriter.Encoding which returns UTF8 as the default encoding for the current StreamWriter instance.

    After that we simply use the instance method StreamWriter.WriteLine() to write a line of characters to the file. Note that you can format the string value that's passed to this method, and that's what we have done in the third call to this method. Let's read from the file using the class StreamReader.

    Using StreamReader to read from the file

    In this example we use the StreamReader class to read the characters of the file aFile.txt in the following manner:

    using System;
    using System.IO;

    namespace MyStreams
    {
      class Class1
      {
        public static void Main()
        {
          try
          {
            FileStream fs = new FileStream("aFile.txt",
    FileMode.OpenOrCreate, FileAccess.ReadWrite,FileShare.None);
            using(StreamReader sr = new StreamReader(fs))
            {
              // first solution
              //Console.WriteLine(sr.ReadToEnd());
              // second solution
              string temp;
              while((temp = sr.ReadLine()) != null)
              {
                Console.WriteLine(temp);
              }
            }
            Console.ReadLine();
          }
          catch(IOException ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
      }
    }

    The result of running the above code example is illustrated in the above screen shot. We have read the contents of the file aFile.txt using an instance of the class StreamReader and by using the method ReadLine(). The instance method StreamReader.ReadLine() reads a line from the file and returns it as a string value, and if there are no more lines to read, it returns a null value.

    In the above code we have created an instance of the StreamReader class and passed the the FileStream instance, which is used to interact with the source file. Then inside the using statement we create a variable of type string that's used in the while loop. The while loop's expression assigns the return value of calling the method ReadLine() of the StreamReader instance to the variable temp. The expression is evaluated to true if the value of the variable temp is not null, which means that a string that represents a line has been assigned to temp. Inside the while body we just print out the value of temp.

    Note that I have commented another solution to return the contents of the file. Using the ReadToEnd() method returns a string that represents all the contents of the stream from the current position to the end of the stream. You can use it but please comment the solution that we have used after you remove the comment of the ReadToEnd() solution.

    More C# Articles
    More By Michael Youssef


       · In this simple article you are going to learn how to write to and read from a file...
     

    C# ARTICLES

    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...
    - Polymorphism in C#
    - Inheritance in C#
    - C# Events Explained
    - C# Delegates Explained
    - C# StreamReader and StreamWriter Explained
    - C# FileStream Explained

    Click Here




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway