Read Binary File into ListBox Problem

Petedu

New member
Joined
Nov 15, 2022
Messages
1
Programming Experience
Beginner
Hi,
Been trying everything to open a binary file into a listbox
and basically just getting a 0 in the box or with the code below
at the line = listBox1.Items.Add(br.ReadBytes(((int)br.BaseStream.Length)));
I will get Byte[]Array in the box, with the streamreader code below that I get
some binary code in the box, really stuck and need help.
Thanks


C#:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
              
              string filename = openFileDialog1.FileName;
              FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
              BinaryReader br = new BinaryReader(fs);
                br.BaseStream.Position = 0;
                for (int i = 0; i < br.BaseStream.Length; i++)
                {
                    listBox1.BeginUpdate();
                    listBox1.Items.Clear();
                    listBox1.Items.Add(br.ReadBytes(((int)br.BaseStream.Length)));
                    listBox1.EndUpdate();
                    
                }
               br.Close();
               fs.Close();
              ///StreamReader streamReader = new StreamReader(filename);
              ///listBox1.Items.Clear();
              ///  List<string> lines = new List<string>();
              ///  string line;
              ///  while ((line = streamReader.ReadLine()) != null)
              ///  { listBox1.Items.Add(line); }

            }
        }
 
This is an example of why it's important to have a clear idea of the logic first - write it down with pen and paper if necessary - and then to write code to explicitly implement that logic. The code you have is nonsensical. That code will start updating the ListBox, clear it, then read the entire file into a byte array, then add that array to the ListBox and then end updating the ListBox... and it will repeat that once for every byte in the file. How does that make sense? It doesn;t, and that's because you wrote that code without a clear idea of what the actually had to do.

Also, when you add an object to a ListBox, what you see is the result of calling ToString on that object. Some types provide specific logic about how to represent objects of that type as a string, e.g. a DateTime will be formatted using the system settings. Most types have no specific logic and will just return the name of the type. That's exactly what you're seeing when you add a byte array to the list. It isn't going to magically turn into some text.

Please provide a FULL and CLEAR explanation of what you're trying to achieve. Saying you want to read a binary file into a ListBox is far too vague. A ListBox is supposed to display a list of items? What are these items? How are the represented by this binary data? How do you expect to convert between the binary data and the items you want to display in the list?
 
Back
Top Bottom