February 27, 2021
Hot Topics:

Accessing Files and Directories

  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Working with Streams

No, I haven't turned this into an article about the great outdoors. Streams have their place with computers as well, although I wouldn't recommend getting your computer near one of the traditional kind. Streams are a concept that have been around for a while, but that are new to Microsoft developers via .NET. A stream is a base class used to abstract the specifics of input and output from the underlying device(s). In general, streams support the ability to read or write. Some streams provide additional capabilities such as seek, which allows navigation forward to a specific location. The device could be a physical file, memory, or the network. List of classes that inherit from the Stream base class are as follows:

  • FileStream—read, write, open, and close files
  • MemoryStream—read and write managed memory
  • NetworkStream—read and write between network connections (System.Net namespace)
  • CryptoStream—read and write data through cryptographic transformations
  • BufferedStream—adds buffering to another stream that does not inherently support buffering

While the streams are used to abstract the input and output from the device, the stream itself is not directly used to read and write data. Instead, a reader or writer object is used to interact with the stream and perform the physical read and write. Here is a list of classes used for reading and writing to streams:

  • BinaryReader and BinaryWriter—read and write binary data to streams
  • StreamReader and StreamWriter—read and write characters from streams
  • StringReader and StringWriter—read and write characters from Strings
  • TextReader and TextWriter—read and write Unicode text from streams

Reading and Writing Text

The following section will use StreamWriter, StreamReader, and FileStream to write text to a file and then read and display the entire contents of the file.

Sample Code to Write and Read a File

using System;using System.IO;namespace CodeGuru.FileOperations{  /// <remarks>  /// Sample to demonstrate writing and reading a file.  /// </remarks>  class WriteReadFile  {   /// <summary>   /// The main entry point for the application.   /// </summary>   [STAThread]   static void Main(string[] args)   {     FileStream fileStream = null;     StreamReader reader = null;     StreamWriter writer = null;     try     {      // Create or open the file      fileStream = new FileStream("c:\\mylog.txt",         FileMode.OpenOrCreate,         FileAccess.Write);      writer = new StreamWriter(fileStream);      // Set the file pointer to the end of the file      writer.BaseStream.Seek(0, SeekOrigin.End);      // Force the write to the underlying file and close      writer.WriteLine(          System.DateTime.Now.ToString() + " - Hello World!");      writer.Flush();      writer.Close();      // Read and display the contents of the file one      // line at a time.      String fileLine;      reader = new StreamReader("c:\\mylog.txt");      while( (fileLine = reader.ReadLine()) != null )       {        Console.WriteLine(fileLine);      }     }     finally     {      // Make sure we cleanup after ourselves      if( writer != null ) writer.Close();      if( reader != null ) reader.Close();     }   }  }}

Page 1 of 3

This article was originally published on September 9, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date