11.6. Randomly Accessing Part of a File

Problem

When reading a file, you sometimes need to move from the current position in a file to a position some number of characters before or after the current position, including to the beginning or the end of a file. After moving to this point, you can add, modify, or read the information at this new point in the file.

Solution

To move around in a stream, use the Seek method. The following method writes the string contained in the variables theFirstLine and theSecondLine to a file in this same order. The stream is then flushed to the file on disk:

public void CreateFile(string theFirstLine, int theSecondLine)
{
    FileStream fileStream = new FileStream("data.txt", 
        FileMode.Create, 
        FileAccess.ReadWrite, 
        FileShare.None);
    StreamWriter streamWriter = new StreamWriter(fileStream);

    streamWriter.WriteLine(theFirstLine);
    streamWriter.WriteLine(theSecondLine);
    streamWriter.Flush( );
    streamWriter.Close( );
    fileStream.Close( );
}

If the following code is used to call this method:

CreateFile("This is the first line.", 1020304050);

the resulting data.txt file will contain the following text:

This is the first line.
1020304050

The following method, ModifyFile, uses the Seek method to reposition the current file position at the end of the first line. A new line of text is then added between the first and second lines of text in the file. Finally, the Seek method is used to place the current position pointer in the file to the end, and a final line of text is written ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.