C#
  Home arrow C# arrow Page 3 - 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 
Moblin 
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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    C# FileStream Explained - Writing to the file using FileStream methods


    (Page 3 of 5 )

    Using the methods of a FileStream instance is very easy. In this section we illustrate how you can write to a file using Write() and WriteByte() methods. Let's take a look at the code

    using System;
    using System.IO;

    namespace MyStreams
    {
      class Class1
      {
        public static void Main()
        {
          try
          {
            FileStream fStream = File.Open("aFile.txt",
    FileMode.OpenOrCreate);
            Console.WriteLine("The FileStream object on the
    aFile.txt:");
            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 writing bytes the
    current position: {0}",fStream.Position);
            if(fStream.CanWrite)
            {
              fStream.WriteByte(65);
              byte[] bytes = new byte[3] {66, 67, 68};
              fStream.Write(bytes, 0, bytes.Length);
              Console.WriteLine("Bytes have been written to the
    file");
            }
            Console.WriteLine("After we have written the bytes the
    current position: {0}",
            fStream.Position);
            fStream.Close();
            Console.ReadLine();
          }
          catch(IOException ex)
          {
            Console.WriteLine(ex.Message);
          }
        }
      }
    }

    When you compile and run the above code you get the following screen shot:

    Navigate to the application folder and open the text file.

    Let's walk through the code step-by-step. The first line in the try block of the Main() method creates a FileStream instance as the return value of calling the method File.Open(), which is passed two values. The first value is a path string to the file and the second value is a FileAccess.OpenOrCreate enumeration value, which opens the file if it's already there or creates a new one. Note that this constructor establishes read/write access to the file.

    The following three lines print out the value of the three properties CanRead, CanWrite and CanSeek respectively. You can use those properties to investigate the capabilities of the stream object in hand. For example, because our stream object (I mean the FileStream object) has been initialized using the constructor that gives read/write access to the file, we got true from CanRead and CanWrite. As to CanSeek: FileStream objects support seeking, so the property CanSeek always returns true -- but when you work with NetworkStream objects, CanSeek always returns false because NetworkStream objects don't support the concept of seeking.

    The next line prints out the value of the property FileStream.position, which returns the current position in the stream. Right now it's zero because we have just created the file and haven't performed any operations yet. Next we check the value of the CanWrite property, which returns true as we just said. Because this stream can write, we use the FileStream.WriteByte() instance method to write a single byte to the stream. Note that this method throws an exception if the object doesn't support writing operations.

    On the next line we create a byte array of three values (66, 67, 68) and write those bytes in one statement using the method FileStream.Write(), which accepts three parameters. The first parameter is the byte array that will be written to the stream, while the second parameter is the starting index of the first array, at which the writing begins. The third parameter defines how many bytes are written to the stream.

    The first line after the if statement prints out the value of the property FileStream.Position which is four because we have written four bytes to the stream. The next line calls the instance method FileStream.Close() which clears the buffer, causing any buffered data to be written to the source file, then closes other resources obtained by this file.

    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

    - Color Transformation in C# GDI+ Programming
    - 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





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