/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Seek.cs -- Demonstrates seeking to a position in a file from the end,
// middle and beginning of a file
//
// Compile this program with the following command line:
// C:>csc Seek.cs
using System;
using System.IO;
using System.Text;
namespace nsStreams
{
public class Seek
{
const string str1 = "Now is the time for all good men to " +
"come to the aid of their Teletype.\r\n";
const string str2 = "The quick red fox jumps over the " +
"lazy brown dog.\r\n";
static public void Main ()
{
FileStream strm;
try
{
strm = new FileStream ("./StrmSeek.txt",
FileMode.Create,
FileAccess.ReadWrite);
}
catch (Exception e)
{
Console.WriteLine (e);
Console.WriteLine ("Cannot open StrmSeek.txt " +
"for reading and writing");
return;
}
// Clear out any remnants in the file
// strm.SetLength (0);
foreach (char ch in str1)
{
strm.WriteByte ((byte) ch);
}
foreach (char ch in str2)
{
strm.WriteByte ((byte) ch);
}
// Seek from the beginning of the file
strm.Seek (str1.Length, SeekOrigin.Begin);
// Read 17 bytes and write to the console.
byte [] text = new byte [17];
strm.Read (text, 0, text.Length);
ShowText (text);
// Seek back 17 bytes and reread.
strm.Seek (-17, SeekOrigin.Current);
strm.Read (text, 0, text.Length);
ShowText (text);
// Seek from the end of the file to the beginning of the second line.
strm.Seek (-str2.Length, SeekOrigin.End);
strm.Read (text, 0, text.Length);
ShowText (text);
}
static void ShowText (byte [] text)
{
StringBuilder str = new StringBuilder (text.Length);
foreach (byte b in text)
{
str.Append ((char) b);
}
Console.WriteLine (str);
}
}
}
//File: StrmSeek.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.
*/