
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
690
|
Chapter 12: Filesystem I/O
The next method, ReadFile, reads the file that we just created. First, the current posi-
tion pointer in the file is moved to the end of the first line (this line contains the
string in the variable
theFirstLine). The ReadToEnd method is invoked reading the
rest of the file (the second and third lines in the file) and the results are displayed:
public static void ReadFile(string theFirstLine)
{
using (StreamReader streamReader = new StreamReader("data.txt"))
{
streamReader.BaseStream.Seek(
theFirstLine.Length + Environment.NewLine.Length, SeekOrigin.Begin);
Console.WriteLine(streamReader.ReadToEnd( ));
}
}
The following text is displayed:
This line added by seeking -12 chars from the end of this file.
This is the last line, added by seeking to the end of the file.
If you are wondering where the line of text that reads:
1020304050
is located, it was overwritten when we did the first Seek while writing data to this file.
Discussion
File seeking is the placement of the pointer to the current location in an opened file
anywhere between—and including—the beginning and ending bytes of a file. Seek-
ing is performed through the use of the
Seek method.
This method returns the new location of the file pointer in the file.
Seeking is performed in one of three ways: