Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata