Link to home
Start Free TrialLog in
Avatar of ray_code
ray_code

asked on

C# Reading file into bytes, then converting it to string, then converting it back to bytes

Hi, I seem to have a problem when reading file into bytes, then converting it to string, then converting it back to bytes.

The code is:

byte[] buff = null;
FileStream fs = new FileStream(System.IO.Path.GetTempPath() + "/myprogram.exe", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(System.IO.Path.GetTempPath() + "/myprogram.exe").Length;
buff = br.ReadBytes((int)numBytes);

 System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

string buffasstring = encoding.GetString(buff);
byte[] prgbk2bytes= encoding.GetBytes(buffasstring);


--
Why are prgbk2bytes bytes are diffrent to the orignal program bytes? How can I get the original program bytes back after converting it to string.

Many thanks

Avatar of Shahan Ayyub
Shahan Ayyub
Flag of Pakistan image

I am getting correct result from your given code, and should work correctly too. Did you do modification some where ??

I had compare each and every byte this way:

            for (int i = 0; i < buff.Length - 1; i++)
            {
                Console.WriteLine(buff[i] + "|" + prgbk2bytes[i]);
            }

Every byte looks same.
ASKER CERTIFIED SOLUTION
Avatar of kris_per
kris_per

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ray_code
ray_code

ASKER

Thanks, right on.