views:

54

answers:

2

Hello,

I have some questions about editing files with c#.

I have managed to read a file into a byte[]. How can I get the ASCII code of each byte and show it in the text area of my form?

Also, how can I change the bytes and then write them back into a file?

For example:

I have a file and I know the first three bytes are letters. How can I change say, the second letter, to "A", then save the file?

Thanks!

+1  A: 

I can only assume that you want to practice writing to/from files by the byte. You need to look into the class BitConverter, there is a lot of help out there for this class. To read in a value you would take in each byte into a byte[]. Once you have your byte[] it would look something like this.

string s = BitConverter.ToString(byteArray);

You can then make your adjustments to your string value, for writing back to the file you'll want to use the GetBytes method.

byte[] newByteArray = BitConveter.GetBytes(s);

Then you could write your bytes back to your file.

jsmith
A: 

If the file is ASCII, then each byte IS the ASCII code. To print the value of the byte to, say, a label, is as simple as this.

If you have read your file into byte[] file;

label1.Text = file[1].ToString();

To change the second letter to A:

file[1] = (byte)'A';

Or

file[1] = (byte)(int)'A';

I'm not sure, I don't have C# on my Mac to test.

But seriously, if it is a text file, you are better reading it in as text, not as a byte[]. And you would probably want to manipulate it using a StringBuilder

Firstly, to read it in as a string:

// Read the file as one string.
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");

string myString = myFile.ReadToEnd();

myFile.Close();

And this will work if the file is unicode as well.

Then, you can get the Unicode values (which for most latin characters is the same as the ASCII value) like so: int value = (int)myString[5]; or so.

You can then write back to a file like so:

System.IO.File.WriteAllText("c:\\test.txt", myString);

If you are going to do heavy modifications on the text, you should use a StringBuilder, otherwise, normal string operations would be fine.

Vincent McNabb
See also "File.ReadAllText", "File.ReadAllLines", "How to: Read Text from a File", "How to: Write Text to a File" on MSDN.
adf88