0

I'm trying to append a base64 string to an existing file. Here's my code:

StreamWriter output = new StreamWriter(file, true, Encoding.ASCII);
output.WriteLine(output.NewLine + str);

Here file is the file path.

For some reason, there is one particular file (a .cs file, if it matters) where the actual text that gets appended is a string of Chinese characters. It works as expected for all the other files I've tested.

kgh
  • 157
  • 1
  • 12
  • 1
    Does the string you're trying to print have any non-ASCII characters in it? That is, any character with a decimal value of > 127? For instance, does it have a Unicode byte order mark (http://en.wikipedia.org/wiki/Byte_order_mark)? – adv12 Jan 12 '15 at 20:05
  • What is `str` in this case? Is it possibly you are overwriting an existing file without truncating and the data is simply what was already there? – Marc Gravell Jan 12 '15 at 20:09
  • 1
    It's almost guaranteed that you're corrupting the file using the wrong (`ASCII`) encoding. Verify that the file is not UTF-8 (or some other encoding). – xxbbcc Jan 12 '15 at 20:11
  • 1
    You've created a StreamWriter with the ASCII encoding, but your Chinese characters are not a part of the ASCII encoding. You may want to try the Unicode encoding, or, it may be safer for you to not corrupt the file by changing its encoding at all. What if its not an ASCII-encoded file to begin with? Encodings can be saved into files through the BOM, which is a flag used to determine the endianness and encoding of the file itself. – Alexandru Jan 12 '15 at 20:24
  • 1
    This will happen if the original file contains a utf-16 BOM. Not uncommon on a Windows machine. – Hans Passant Jan 12 '15 at 20:25

1 Answers1

0

Following the multiple suggestions in the comments, I replaced Encoding.ASCII with the file's encoding, which I look up using 2Toad's answer here. That solved the problem.

Community
  • 1
  • 1
kgh
  • 157
  • 1
  • 12