How does one roll back a readline from a text file?

Recommended Answers

All 3 Replies

Use the Seek method example

Sorry to be resurrecting this post, but I have been buisy lately, and didn't have time to persue this any farther. Can anybody provide some code for how to roll back a readline? I am currently dealing with a FileStream and a reader stream(i foreget what it was called) and every time I try to use this seek method I end up halfway between the previous record and the one I am trying to read again. I have been trying to incorporate the length of the string into the calculation. The code I have would be convoluted and bulky, so best if we start over from scratch.

I have been looking at an example on MSDN, and I have some code. Lines 27 through 30 are throwing overflow exceptions. I do not know why I cannot use the current location in the file to seek from.

using System;
using System.IO;

public class FSSeek {
    public static void Main() {
        long offset;
        int nextByte;

        // alphabet.txt contains "abcdefghijklmnopqrstuvwxyz" 
        using (FileStream fs = new FileStream("stuff.txt", FileMode.Open, FileAccess.Read)) {
            for (offset = 1; offset <= fs.Length; offset++) {
                fs.Seek(-offset, SeekOrigin.End);//seeks from end backwards
                Console.Write(Convert.ToChar(fs.ReadByte()));
            }
            Console.WriteLine();

            for (offset = 0; offset <= fs.Length - 1; offset++) {
                fs.Seek(offset, SeekOrigin.Begin);//seeks from beginning forwards
                Console.Write(Convert.ToChar(fs.ReadByte()));
            }
            Console.WriteLine();

            //fs.Seek(0, SeekOrigin.Begin);//go back to beginning
            fs.Seek(13, SeekOrigin.End);//go to middle of file


            for (offset = 0; fs.Seek(offset, SeekOrigin.Current) > 0; offset++) {
                fs.Seek(-offset, SeekOrigin.Current);//seeks from current backwards
                Console.Write(Convert.ToChar(fs.ReadByte()));
            }

                fs.Seek(20, SeekOrigin.Begin);

            while (( nextByte = fs.ReadByte() ) > 0) {
                Console.Write(Convert.ToChar(nextByte));
            }
            Console.WriteLine();
        }
    }
}
// This code example displays the following output: 
// 
// zyxwvutsrqponmlkjihgfedcba 
// uvwxyz
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.