Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

Detect end of file

I currently have:
try
{
  for (; ; )
  {
    y = r.ReadByte();
  }
}
catch (EndOfStreamException)
{
  //end of file
}

Open in new window

Is there a better way? I feel I shouldn't be using catch for an expected exception.
0
deleyd
Asked:
deleyd
  • 2
3 Solutions
 
Jacques Bourgeois (James Burger)Commented:
r looks like a BinaryReader. Could we see the call to its constructor so that we can know what is the underlying stream? Some streams, such as the FileStream, have a marker for the end of the stream. You could be able to catch the condition through the BaseStream.
0
 
deleydAuthor Commented:
using (FileStream fs = new FileStream(fn, FileMode.Open, FileAccess.Read))
{
  using (BinaryReader r = new BinaryReader(fs))
  {
    try
    {
      for (; ; )
      {
        y = r.ReadByte();
      }
    }
    catch (EndOfStreamException)
    {
      //end of file
    }

Open in new window

0
 
käµfm³d 👽Commented:
How about modding line 7 to be:

for ( ; fs.Position < fs.Length; )

Open in new window

0
 
Jacques Bourgeois (James Burger)Commented:
As I expected. You cannot know where the cursor is in the BinaryStream itself, but you can in the underlying FileStream.

     while (! (fs.Position==fs.Length))
      {
        y = r.ReadByte();
      }

Open in new window


You might have to adjust fs.Length plus 1 or minus 1, I do not remember if Position starts at index 0 or 1.
                        {}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now