-3

I have to write the below binary array into a file:

byte[] data = new byte[] { 0x55, 0xAA, 0x02};

I want to put the exact data into the file (55,AA,02). Please let me know how to do it.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user209293
  • 889
  • 3
  • 18
  • 27
  • Possible duplicates: http://stackoverflow.com/questions/381508/can-a-byte-array-be-written-to-a-file-in-c, http://stackoverflow.com/questions/128674/what-is-the-most-efficient-way-to-save-a-byte-array-as-a-file-on-disk-in-c, http://stackoverflow.com/questions/224239/whats-the-best-way-to-write-a-short-array-to-a-file-in-c – Cody Gray - on strike Dec 23 '10 at 08:04
  • Use BitConverter.ToString(data) to create a string that you can write to a text file. – Hans Passant Dec 23 '10 at 11:12

4 Answers4

8

You can use the Stream.Write(byte[] buffer) overload.

And even easier,

   System.IO.File.WriteAllBytes("fileName", data);
H H
  • 263,252
  • 30
  • 330
  • 514
  • When i use the aboe function some non readable characters are displayed in the file. I want the data to be displayed exactly. – user209293 Dec 23 '10 at 07:58
  • 3
    It's because you're writing characters, which are not printable. 0x02 is not a 'printable' character code. You want to use a *hex editor* to view your output file and verify it wrote data exactly. – Andrei Sosnin Dec 23 '10 at 08:12
  • @user209293 Your data has non-printable codes when viewed a s ASCII/ANSI/UTF8. So you'll have to more precise in what result you want. Currently your comments contradict the req in the question. – H H Dec 23 '10 at 14:56
1

Please try the following:

FileStream fs = new FileStream(Application.StartupPath + "\\data.bin", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
byte[] data = new byte[] { 0x55, 0xAA, 0x02 };
bw.Write(data);
bw.Close();
fs.Close();
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Rajesh Kumar G
  • 1,424
  • 5
  • 18
  • 30
0

You can use File.WriteAllBytes(string path, byte[] bytes).

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • When i use the aboe function some non readable characters are displayed in the file. I want the data to be displayed exactly – user209293 Dec 23 '10 at 08:01
  • @user209293, use a hex editor. Don't expect a text editor to display you non printable characters like 0x02. – Darin Dimitrov Dec 23 '10 at 08:14
  • If you don't want to write the exact data, but rather the string representation of your byte values into a file, maybe you should rephrase your question. – Botz3000 Dec 23 '10 at 08:20
0

Iirc you can use

string content = BitConverter.ToString(data);

to retrieve a string containing the content and then write that string to the File you want.

Anton
  • 5,323
  • 1
  • 22
  • 25