vb.net - peek or read

how can I know the last HEX byte of a 2GB binary file without opening the whole file..
is there a easy way for doing this without running into memory problems?
Who is Participating?
Robert SchuttConnect With a Mentor Software EngineerCommented:
Below code seems to do what you need, in C#
        private void button2_Click(object sender, EventArgs e) {
            FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
            fs.Seek(-1, SeekOrigin.End);
            long pos = fs.Position;
            uint ch = (uint)fs.ReadByte();
            long pos2 = fs.Position;
            label1.Text = string.Format("pos: {1}, byte: {0}, pos after: {2}", ch.ToString(), pos, pos2);

Open in new window

AndyAinscowFreelance programmer / ConsultantCommented:
As far as I know you will have to open the complete file and move (read) to the end - which you could do in smaller chuncks eg with a 1MB buffer you read the file into in a loop until you get the final section.
XK8ERAuthor Commented:
is there a faster way to just read the last bytes?
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

AndyAinscowFreelance programmer / ConsultantCommented:
I can think of a couple.
Use a different language (eg C++) where you can access the file via pointer so you can rapidly move to the end by incrementing the pointer without having to read to a buffer.
Work out which disc sector the last segment of the file occupies then read the disc sector directly.  (The OP system might not let you do this.)
XK8ERAuthor Commented:
so there is not really any other way huh?
AndyAinscowFreelance programmer / ConsultantCommented:
Nice one - I'd been looking into the wrong classes and not found a way to set the position in the stream.  (Sometimes the documentation seems to be there to make things as difficult as possible to find).
Robert SchuttSoftware EngineerCommented:
@AndyAinscow, it can be troubling to navigate those pages, yes, especially when you're not certain where to look. I remembered there had to be a Seek but apart from having to find the exact class it is in, I also wondered if that would do exactly what you described: read through the whole file, which would make it rather useless of course. So after I found the right doc page, I decided to double check and test with a few fairly big files on a USB stick and the speed of that convinced me it was indeed jumping directly to the end, as it would do in C/C++.

@XK8ER, thanks for the grade!

PS: Now, looking back at my own test code, I found you can also simply replace Seek() with:
fs.Position = fs.Length - 1;

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.