Click to See Complete Forum and Search --> : Reading And Writing Binary Files


code?
February 15th, 2010, 03:52 PM
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.

rliq
February 15th, 2010, 05:38 PM
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);