Demonstrates attaching a StreamWriter object to a stream

image_pdfimage_print
   
 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// StrmWrtr.cs -- Demonstrates attaching a StreamWriter object to a stream
//
//                Compile this program with the following command line:
//                    C:>csc StrmWrtr.cs
using System;
using System.IO;

namespace nsStreams
{
    public class StrmWrtr
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            FileStream strm;
            StreamWriter writer;
            try
            {
// Create the stream
                strm = new FileStream (args[0], FileMode.OpenOrCreate, FileAccess.Write);
// Link a stream reader to the stream
                writer = new StreamWriter (strm);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            strm.SetLength (0);
            while (true)
            {
                 string str = Console.ReadLine ();
                 if (str.Length == 0)
                     break;
                 writer.WriteLine (str);
            }
            writer.Close ();
            strm.Close ();
        }
    }
}


           
         
     


This entry was posted in File Stream. Bookmark the permalink.