CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2006
    Posts
    306

    Reading And Writing Binary Files

    Okay so I'm sure you've all played games. Maybe some of you wanted to see what the files looked like.

    Some game-files are .ini with text, and then there are some which you can't open in a normal text editor. You would have to use a hex editing tool, but how would you accomplish something similar in C#?

    Would is be practical to use StreamReader and StreamWriter or something that reads bytes?

    Some links and samples would be nice.

  2. #2
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: Reading And Writing Binary Files

    Code:
                Byte[] data;
    
                // read all of a file (upto 2GB-1 in size)
                using (FileStream fs = new FileStream(@"C:\oldFile.bin", FileMode.Open))
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        data = br.ReadBytes((Int32)fs.Length);
    
                        // if you know the internal format of the file, you can loop here instead of reading it all at once
                        // and read a bit at a time using br.ReadDouble(), br.ReadInt16() etc
    
                        br.Close();
                    }
    
                    fs.Close();
                }
    
                // write it all to another file
                File.WriteAllBytes(@"C:\newFile.bin", data);
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured