Reputation: 1189
I saw this code example:
using (FileStream fStream = File.Open(@"C:\myMessage.dat", FileMode.Create))
{
string msg = "Helloo";
byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);
foreach (var a in msgAsByteArray)
{
Console.WriteLine($"a: {a}");
}
// Write byte[] to file.
fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length);
// Reset internal position of stream.
fStream.Position = 0;
// Read the types from file and display to console.
Console.Write("Your message as an array of bytes: ");
byte[] bytesFromFile = new byte[msgAsByteArray.Length];
for (int i = 0; i < msgAsByteArray.Length; i++)
{
bytesFromFile[i] = (byte)fStream.ReadByte();
Console.Write(bytesFromFile[i]);
}
// Display decoded messages.
Console.Write("\nDecoded Message: ");
Console.WriteLine(Encoding.Default.GetString(bytesFromFile));
And the result of Console.WriteLine($"a: {a}") is this:
a: 72
a: 101
a: 108
a: 108
a: 111
a: 111
1. I thought byte[] is composed of many each unit of byte. But each byte is represented in integer number. That numbers must be corresponding ASCII characters. In C#, byte array means data represented in ASCII?
2. Is the file myMessage.dat composed of binary data composed of only 0 and 1? But when I open myMessage.dat with the text editor, it's showing Helloo text string. What's the reason for this?
Upvotes: 1
Views: 3388
Reputation: 51653
You explicitly converted the "Halloo" to bytes with Encoding.Default.GetBytes()
- that is kindof like converting it to its ascii value but heeding the default encoding on your system.
byte[] myBytes = new [] {0,7,12,3,9,30}
into a file and open that with your textedit you will get nonreadable texts as "normal text" starts around 32 , before are f.e. tabs, bells, line feeds and other special non printable characters. See f.e. NonPrintableAsciiUpvotes: 2