Sign in to follow this  
harleking

Reading and writing hex in C# question

Recommended Posts

I'm writing a program in C# that will modify the hex code of a file. I'd like to read the value in a predetermined, nonvariable address display it and allow the user the change it. I'm familiar with file i/o with strings but not with hex (and modifying something at a specific address). Could anyone point me to some documentation that explains how to go about this? Thanks.

Share this post


Link to post
Share on other sites
You need to use the FileStream class to read your file. You can use the Seek method to position the read cursor at a specific point in the file, and then use the Read/ReadByte methods to read in one or more bytes of data. If you would like to display the results as hex-strings, you can use the Byte.ToString method passing "x" as your format specifier argument.

Share this post


Link to post
Share on other sites
I ran into another problem. I'm trying to use a menu tool strip to implement open file and save file functions. I declared my FileStream outside all functions to make it accessible to the open and save functions. I instanciated FileStream in the open function, but I need to use it again during save. My problem is that FileStream.CanWrite is true in the open function but false in the other. I really can't figure out why, and I don't know how to give save full access to save. What am I doing wrong?

Share this post


Link to post
Share on other sites
Sounds like your FileStream isn't actually one object, but two separate objects. Or you didn't open the FileStream for both read and write when you initially opened it.

What I would do, though, is to open a FileStream, and read the entire file into memory, the disposing the FileStream. When saving, I would re-create a file called <outputname>.tmp, write all the edited data to that, dispose that file, and then using Replace to replace the destination file with the contents of the tmp file.

Assuming you have enough RAM and disk for doing this, it's a MUCH safer route to go.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this