Convert file to binary in C#

I am trying to write a program that transfers a file through sound (kind of like a fax). I broke up my program into several steps:

  1. convert file to binary
  2. convert 1 to a certain tone and 0 to another
  3. play the tones to another computer
  4. other computer listens to tones
  5. other computer converts tones into binary
  6. other computer converts binary into file.

However, I can’t seem to find a way to convert a file to binary. I found a way to convert a string to binary using

public static string StringToBinary(string data)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in data.ToCharArray())
    {
        sb.Append(Convert.ToString(c, 2).PadLeft(8,'0'));
    }
    return sb.ToString();
}

From http://www.fluxbytes.com/csharp/convert-string-to-binary-and-binary-to-string-in-c/ .
But I can’t find out how to convert a file to binary (the file could be of any extension).

So, how can I convert a file to binary? Is there a better way for me to write my program?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Why don’t you just open the file in binary mode?
this function opens the file in binary mode and returns the byte array:

private byte[] GetBinaryFile(filename)
{
     byte[] bytes;
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
     {
          bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
     }
     return bytes;
}

then to convert it to bits:

byte[] bytes = GetBinaryFile("filename.bin");
BitArray bits = new BitArray(bytes);

now bits variable holds 0,1 you wanted.

or you can just do this:

private BitArray GetFileBits(filename)
{
     byte[] bytes;
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
     {
          bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
     }
     return new BitArray(bytes);
}

Or even shorter code could be:

   private BitArray GetFileBits(filename)
    {
         byte[] bytes = File.ReadAllBytes(filename);
         return new BitArray(bytes);
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x