Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

asp.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...