1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Need help reading binary file

Discussion in 'C, C++, C#' started by tsmith2471, Mar 5, 2013.

  1. tsmith2471

    tsmith2471 Newbie

    Joined:
    Oct 21, 2012
    Messages:
    14
    Likes Received:
    4
    Trying to read a binary file and cannot put the bytes into a string. Does anybody have and advice? Thanks
    Code:
     BinaryReader binaryreader = new BinaryReader(File.OpenRead(file location));
    
                while(binaryreader.Read() > 0)
                {
                                    
                        byte[] empIdBytes = new byte[3];
                        binaryreader.Read();
                        String empId = new String(empIdBytes);
                        byte[] empIndBytes = new byte[1];
                        binaryreader.Read();
                        String empInd = new String(empIndBytes);
                        
     
  2. hatemachine

    hatemachine Regular Member

    Joined:
    Jan 14, 2011
    Messages:
    271
    Likes Received:
    1,138
    • Thanks Thanks x 1
  3. tsmith2471

    tsmith2471 Newbie

    Joined:
    Oct 21, 2012
    Messages:
    14
    Likes Received:
    4
    Thanks for the link
     
  4. theMagicNumber

    theMagicNumber Regular Member

    Joined:
    May 13, 2010
    Messages:
    345
    Likes Received:
    195
    This won't work unless the file contains only strings.
    To read a binary file, the structure has to be know.

    Code:
     using (BinaryReader bin = new BinaryReader(File.Open("test.dat", FileMode.Open)))
                {
                    while (bin.BaseStream.Position < bin.BaseStream.Length)
                    {
                        int test1 = bin.ReadInt32();
                        byte test2 = bin.ReadByte();
                        string test3 = bin.ReadString();
                    }
                }