Click here to Skip to main content
15,908,254 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Using c# when I convert a pdf ,exe,jpeg etc files to its corresponding binary 0,1. File size is greater than its original size. What is the reason for it?

Please help me to solve this problem here is the code i have used.

C#
try
{
  byte[] fileBytes = File.ReadAllBytes(textBox1.Text);
  StringBuilder sb = new StringBuilder();

  foreach (byte b in fileBytes)
  {
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
  }

  File.WriteAllText("outputFilename", sb.ToString());
}
catch (OutOfMemoryException )
{

}
Posted
Updated 6-May-11 5:34am
v3

You are not converting it to binary. But to text. You read all bytes from a file, and then convert it to text. 1 byte is converted to 8 char. That is why it gets bigger then the original file.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-May-11 12:35pm    
...And makes no point, John's right. My 5.
--SA
Kim Togo 6-May-11 13:00pm    
Thanks
Every file (even text files) are "binary" when you get right down to brass tacks, because every byte in the file is a byte, regardless of how it's presented to the user. As Kim has already pointed ut, you're reading the original file in as text, and creating the output file as text, and that's why the file is bigger. If you just want to copy a file, use System.IO.File.Copy(). There's no point in doing what you're trying to do unless you're just trying to learn some more involved file handling stuff.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 6-May-11 12:34pm    
Finally I can here someone who said that "text file" is binary! And so on. My 5.
--SA
Kim Togo 6-May-11 13:00pm    
Good answer John. My 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900