I advise you to use the classes
System.IO.BinaryWriter
and
System.IO.BinaryReader
(and not stream classes). They can read and write both binary and text data. Note that all data is essentially binary. Text data just a sort of binary.
То write or read data, use overloaded methods
Write
or
Read
for each data type, including string.
Now, about the text. Pay attention that the writer and reader constructors allow to specify encoding. This is important, because the text can be written in different encoding. Make sure encodings match when you write and read the same data.
See:
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx[
^].
This is how your code sample should look:
using (
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(
System.IO.File.Open(
"my_binary_sample.rda",
System.IO.FileMode.CreateNew),
System.Text.Encoding.UTF8))
{
double[] binary = new double[] { 123, 456, 8, 9, 0, 7, 6, 5, 5, 4, 3, 3 };
writer.Write("Line 1");
writer.Write("Line 2");
writer.Write("Line 3");
foreach (double val in binary)
writer.Write(val);
}
Check out "
using
". It is important as it guarantees closing of streams even if exception occurs.
—SA