-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.

2

4 Answers 4

9

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

And even easier,

   System.IO.File.WriteAllBytes("fileName", data);
Sign up to request clarification or add additional context in comments.

3 Comments

When i use the aboe function some non readable characters are displayed in the file. I want the data to be displayed exactly.
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.
@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.
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();

1 Comment

open the output file in microsoft visual studio,u will see the result that what do you want in binary format
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.

Comments

0

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

3 Comments

When i use the aboe function some non readable characters are displayed in the file. I want the data to be displayed exactly
@user209293, use a hex editor. Don't expect a text editor to display you non printable characters like 0x02.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.