A simple key-to-disk utility that demonstrates a StreamWriter


   
 
/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* A simple key-to-disk utility that 
   demonstrates a StreamWriter. */ 
 
using System; 
using System.IO; 
  
public class KtoD { 
  public static void Main() { 
    string str; 
    FileStream fout; 
 
    try { 
      fout = new FileStream("test.txt", FileMode.Create); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "Cannot open file."); 
      return ; 
    } 
    StreamWriter fstr_out = new StreamWriter(fout); 
 
    Console.WriteLine("Enter text ('stop' to quit)."); 
    do { 
      Console.Write(": "); 
      str = Console.ReadLine(); 
 
      if(str != "stop") { 
        str = str + "
"; // add newline 
        try { 
          fstr_out.Write(str); 
        } catch(IOException exc) { 
          Console.WriteLine(exc.Message + "File Error"); 
          return ; 
        } 
      } 
    } while(str != "stop"); 
 
    fstr_out.Close(); 
  } 
}


           
         
     


Demonstrates attaching a StreamWriter object to a stream

   
 
/*
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 ();
        }
    }
}


           
         
     


Demonstrates attaching a StreamReader object to a stream

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

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

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

namespace nsStreams
{
    public class StrmRdr
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            FileStream strm;
            StreamReader reader;
            try
            {
                // Create the stream
                strm = new FileStream (args[0], FileMode.Open, FileAccess.Read);
                // Link a stream reader to the stream
                reader = new StreamReader (strm);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            while (reader.Peek() >= 0)
            {
                string text = reader.ReadLine ();
                Console.WriteLine (text);
            }
            reader.Close ();
            strm.Close ();
        }
    }
}


           
         
     


The use of a buffered stream to serve as intermediate data holder for another stream

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// BufStrm.cs — demonstates the use of a buffered stream to serve
// as intermediate data holder for another stream.
//
// Compile this program with the following command line:
// C:>csc BufStrm.cs
using System;
using System.IO;

namespace nsStreams
{
public class BufStrm
{
static public void Main ()
{
FileStream strm;
try
{
strm = new FileStream (“./BufStrm.txt”,
FileMode.OpenOrCreate,
FileAccess.Write);
}
catch (Exception e)
{
Console.WriteLine (e.Message);
Console.WriteLine (“Cannot open ./BufStrm.txt”);
return;
}
strm.SetLength (0);
BufferedStream bstrm = new BufferedStream (strm);
string str = “Now is the time for all good men to ” +
“come to the aid of their Teletype.
“;
byte [] b;
StringToByte (out b, str);
bstrm.Write (b, 0, b.Length);
// Save the current position to fix an error.
long Pos = bstrm.Position;
Console.WriteLine (“The buffered stream position is ”
+ bstrm.Position);
Console.WriteLine (“The underlying stream position is ”
+ strm.Position);
str = “the quick red fox jumps over the lazy brown dog.
“;
StringToByte (out b, str);
bstrm.Write (b, 0, b.Length);
Console.WriteLine (”
The buffered stream position is ” +
bstrm.Position);
Console.WriteLine (“The underlying stream position is still ”
+ strm.Position);
// Fix the lower case letter at the beginning of the second string
bstrm.Seek (Pos, SeekOrigin.Begin);
b[0] = (byte) 'T';
bstrm.Write (b, 0, 1);
// Flush the buffered stream. This will force the data into the
// underlying stream.
bstrm.Flush ();
bstrm.Close ();
strm.Close ();
}
//
// Convert a buffer of type string to byte
static void StringToByte (out byte [] b, string str)
{
b = new byte [str.Length];
for (int x = 0; x < str.Length; ++x) { b[x] = (byte) str [x]; } } } } //File: BufStrm.txt /* Now is the time for all good men to come to the aid of their Teletype. The quick red fox jumps over the lazy brown dog. */ [/csharp]

Asynchronously reads a stream

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Async.cs — Asynchronously reads a stream
//
// Compile this program with the following command line;
// C:>csc Async.cs
//
using System;
using System.IO;
using System.Threading;

namespace nsStreams
{
public class Async
{
static Byte [] data = new Byte[64];
static bool bDone = true;

static public void Main (string [] args)
{
if (args.Length == 0)
{
Console.WriteLine (“Please enter a file name”);
return;
}
FileStream istrm;
try
{
istrm = new FileStream (args[0], FileMode.Open,
FileAccess.Read, FileShare.Read,
data.Length, true);
}
catch (FileNotFoundException)
{
Console.WriteLine (args[0] + ” was not found”);
return;
}
catch (Exception)
{
Console.WriteLine (“Cannot open ” + args[0] +
” for reading”);
return;
}
AsyncCallback cb = new AsyncCallback (ShowText);
long Length = istrm.Length;
int count = 0;
while (true)
{
if (Length == istrm.Position)
break;
if (bDone)
{
bDone = false;
istrm.BeginRead (data, 0, data.Length, cb, count);
++count;
}
Thread.Sleep (250);
}
istrm.Close ();
}
static public void ShowText (IAsyncResult result)
{
for (int x = 0; x < data.Length; ++x) { if (data[x] == 0) break; Console.Write ((char) data[x]); data[x] = 0; } bDone = true; } } } [/csharp]

illustrates reading and writing text data


   
 
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_16.cs illustrates reading and writing text data
*/

using System;
using System.IO;

public class Example15_16 
{

  public static void Main() 
  {

    // create a new file to work with
    FileStream outStream = File.Create("c:TextTest.txt");

    // use a StreamWriter to write data to the file
    StreamWriter sw = new StreamWriter(outStream);

    // write some text to the file
    sw.WriteLine("This is a test of the StreamWriter class");

    // flush and close
    sw.Flush();
    sw.Close();

    // now open the file for reading
    StreamReader sr = new StreamReader("c:TextTest.txt");

    // read the first line of the file into a buffer and display it
    string FirstLine;
  
    FirstLine = sr.ReadLine();
    Console.WriteLine(FirstLine);

    // clean up
    sr.Close();

  }

}



           
         
     


StreamReader And Writer

/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;

namespace Client.Chapter_11___File_and_Streams
{
public class StreamReaderAndWriter {
static void Main(string[] args)
{
StreamReader MyStreamReader = new StreamReader(@”c:ProjectsTesting.txt”);

//If you need to control share permissions when creating a file you
//use FileStream with StreamReader
FileStream MyFileStream = new FileStream(@”c:ProjectsTesting.txt”, FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader MyStreamReader2 = new StreamReader(MyFileStream);

MyFileStream.Close();
MyStreamReader2.Close();

//The easiest way to Read a stream is to use the ReadLine method.
//This method reads until it gets to the end of a line, but …
//it does not copy the carriage return line feed /n/r.
string MyStringReader = MyStreamReader.ReadLine();

//You can also read the whole file by using the following
string MyStringReadToEOF = MyStreamReader.ReadToEnd();

//The other route is to read one character at a time
int[] MyArrayOfCharacters = new int[100];

for (int i = 0; i < 99; i++) { MyArrayOfCharacters[i] = MyStreamReader.Read(); } MyStreamReader.Close(); } } } [/csharp]