Raghav55
Raghav55

Reputation: 3135

how to write a new line character using binarywriter

I am using a bianryreader to read the contents of binary file and convert the binary data to a double array.

Contents of binary file

Header
Axis values
Points values

After the Axis values are written , the points values to be written in a new line. I am just writing a sample how i am creating a new line

BinaryWriter aBinaryWriter = new BinaryWriter(new FileStream("c:\\newline.txt",FileMode.OpenOrCreate));
aBinaryWriter.Write("\r\n");
aBinaryWriter.Close();

writing parts works fine.

Reading part:

I want to read the point values, so I moving the file pointers by 2 location reason to skip the new line character. But What I am seeing is there are 3 characters with the ascii value "2,13,10".

  1. What is the reason to have 3 ascii values?
  2. How to introduce a new line character("\r\n") in a binary file.

Code:

BinaryReader abinRead = new BinaryReader(new FileStream("c:\\newline.txt",FileMode.OpenOrCreate));
while (abinRead.PeekChar() != -1)
{
    char aChar = abinRead.ReadChar();
    Console.WriteLine(aChar);
 }
 abinRead.Close();

Upvotes: 1

Views: 6302

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063619

The mistake here is using BinaryWriter. If you are writing a text file, use a TextWriter, for example StreamWriter:

using (var writer = new StreamWriter("foo.txt"))
{
    writer.Write(someString);
    writer.Write(someDouble);
    writer.WriteLine();
}

A BinaryWriter is only really intended for use with BinaryReader, for following a very specific set of binary rules. In most cases even when working with binary, the raw Stream is more versatile. But writing a text file via BinaryWriter is ... well, not impossible (you could do the Encoding yourself etc) - but it isn't what it is designed for.

Upvotes: 2

SLaks
SLaks

Reputation: 887837

BinaryWriter.Write() writes a length-prefixed string.
The first byte is the length of the string.

Upvotes: 3

Related Questions