C#
  Home arrow C# arrow Page 4 - C# FileStream Explained
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# FileStream Explained
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 20
    2007-01-31

    Table of Contents:
  • C# FileStream Explained
  • The FileStream Class
  • Writing to the file using FileStream methods
  • Reading from the file using FileStream methods
  • Use the Seek() method

  • 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

    AT&T devCentral & BlackBerry(r) Webcast Series: BlackBerry and GPS -Build Location Awareness into your BlackBerry Applications, July 10th -1:00PM EST. Register Today!

    C# FileStream Explained - Reading from the file using FileStream methods


    (Page 4 of 5 )

    In the following example we are going to read the bytes of the file we just created.

    using System;
    using System.IO;

    namespace MyStreams
    {
      class Class1
      {
        public static void Main()
        {
          try
          {
            using(FileStream fStream = File.OpenRead("aFile.txt"))
            {
              Console.WriteLine("Investigating the file
    capabilities");
              Console.WriteLine("Can Read? {0}", fStream.CanRead);
              Console.WriteLine("Can Write? {0}", fStream.CanWrite);
              Console.WriteLine("Can Seek? {0}", fStream.CanSeek);
              Console.WriteLine("Before we start reading bytes the
    current position: {0}",
              fStream.Position);
              if(fStream.CanRead)
              {
                // returns the bytes of the file
                byte[] bytes = new byte[fStream.Length];
                fStream.Read(bytes, 0, bytes.Length);
                foreach(byte b in bytes)
                {
                  Console.Write(" {0} ", b);
                }
                /* This code can be used in place of the above code
                * int temp = 0;
                while((temp = fStream.ReadByte()) != -1)
                {
                  Console.WriteLine(temp);
                }*/

                /* This code can be used in place of the above while
    statement
                * while(fStream.Position < fStream.Length)
                  {
                    Console.Write(" {0} ", fStream.ReadByte());
                  }
                * */
              }
              Console.WriteLine("nAfter we have read the bytes the
    current position: {0}",fStream.Position);
              Console.ReadLine();
            }
          }
          catch(IOException ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
      }

    Compile and run the code to get the following screen shot.

    As you can see, we have read the bytes of the file (65 66 67 68). Note that there are  three ways to read the bytes of the file which you can try. The one I have used for this example is creating a byte array then using the FileStream.Read() method, which accepts three parameters. The array that is used to store the bytes reads from the file and the index of the array at which to begin to store the bytes, then the last parameter states how many bytes you want to read and store into the array. The next foreach statement prints out each byte value stored in the array. Note that I have used the instance property FileStream.Length as the length of the byte array that's used to store the bytes of the file. The Length property returns the size of the file in bytes.

    The next commented solution uses a while loop. the FileStream.ReadByte() instance method reads a byte (but returns it as int value), advances the position of the stream by 1 and returns -1 if there are no bytes to return. So the while loop expression (temp = fStream.ReadByte()) != -1) prints out the byte as long as the value assigned by ReadByte() to temp is not -1.

    The last solution also uses a while loop, but this time the while loop expression (fStream.Position < fStream.Length) evaluates to true as long as the position of the stream is less than the length of the stream. Note that we have used a using statement with the FileStream instance to ensure an auto call to the FileStream.Close() method.

    More C# Articles
    More By Michael Youssef


       · Do you know what a FileStream instance is? No? Ok read the article :)
       · I just can't stop reading your articles. Can't you write a book about C# please? I'm...
       · Hi Marie,I wish I can write a book but this needs time and there are many...
       · Hi, This is nice to study ur article.Your explanation is very good.If u...
       · I found this article very useful to get to know about the File Streams in a quick...
       · Hello Sarav,What exactly the topics you would like me to write about?Have you...
     

    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

    Iron Speed




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