/*
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.\r\n";
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.\r\n";
StringToByte (out b, str);
bstrm.Write (b, 0, b.Length);
Console.WriteLine ("\r\nThe 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.
*/
|