I need to generate a file that will be read by another system. For this reason, it should be in binary, not text with some encoding.
Here's the code I'm using:
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write("Some text" + Environment.NewLine);
writer.Write("Some more text" + Environment.NewLine);
}
}
When I open the file and look at it, I can see some special character at the start of each line, similar to this (hard to paste it here, since it doesn't show the same):
~Some text
~Some more text
What am I doi开发者_如何学编程ng wrong/forgetting?
Thanks for your help.
There's no such concept as text without an encoding. It's like wanting to save an abstract image to disk without specifying any image format. (Even "raw" is a kind of encoding for images - you need to agree on a way of communicating the width, height, byte order, colour depth somehow.)
I suggest you just fix on one encoding (e.g. Encoding.Unicode
or Encoding.UTF8
) and write the text that way.
As for why BinaryWriter.Write(text)
is putting "special characters" at the start of each line, did you check the documentation for what it does?
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
and
A length-prefixed string represents the string length by prefixing to the string a single byte or word that contains the length of that string. This method first writes the length of the string as a UTF-7 encoded unsigned integer, and then writes that many characters to the stream by using the BinaryWriter instance's current encoding.
So what you're seeing is the length-prefix... but then it will use whatever encoding you've set up for the BinaryWriter
.
精彩评论