Problem Parsing Text with BinaryReader

Hello. I’m having a problem trying to parse a file using BinaryReader. Specifically, when I try to use ReadInt32(), it reads in “too much.”

My file (midi event data) is formatted where each line is a series of integers and strings like so:

0 0 non 49 127 0
2880 2880 noff 49 0 0

Each field is delimited by a tab. Problem is, ReadInt32() reads in 4 bytes or, in the case of the first line: 0 (space) 0 (space). I’ve done file parsing before, and it seemed to recognize the white space and only give me the 0 when I try to read in an integer. Can anyone provide help here? Thanks in advance.

Is the file you’re reading and ASCII file? If it is (which it look like) you might want to try a StreamReader as BinaryReader is more for binary files.

Just read a line, split it on the tabs, and use Int32.Parse() to convert it.

Thanks for the response! I’ve also tried StreamReader, but the problem is that each integer can be of variable characters long, and to my knowledge, StreamReader only supplies a Read() member which will grab the next character only, or you can supply it a number of chars to grab.

I suppose I could use the Peek() function until I get to a tab, then I would know the number of chars to read in…is this the best way to do this?

You can use ReadLine() to read until the end of the line. You can then parse the string like this,

using(StreamReader sr = new StreamReader("File.txt"))
{
  string line;
  while( (line = sr.ReadLine()) != null )
  {
    string[] list = line.Split( new Char[]{'\t'} );
    int value1 = Int32.Parse(list[0]);
    int value2 = Int32.Parse(list[1]);
    ...
  }
}

You are my personal savior…it worked brilliantly. Thank you so much for your help.

How can you change the code to only read a specific line in the text file?

I see currently it does a full read not just a specific line in the file.

Just wondering.

Great resource on the forum!

Thanks again for post the reply to this post.