C#'\n'以不同于预期的字节保存

Oli*_*ara 5 c# string

如果我将此字符串保存到文本文件中;

你好,这是一个测试消息

\n字符保存为HEX [5C 6E]我希望将其保存为[0A].

我相信这是一个编码问题?

我在用;

// 1252 is a variable in the application
Encoding codePage = Encoding.GetEncoding("1252");
Byte[] bytes = new UTF8Encoding(true).GetBytes("Hello this \\n is a test message");
Byte[] encodedBytes = Encoding.Convert(Encoding.UTF8, codePage , bytes);
Run Code Online (Sandbox Code Playgroud)

所有这些都在FileStream范围内,并使用fs.Write将encodedBytes写入文件.

我试过使用\ r \n但是有相同的结果.

有什么建议?

谢谢!

编辑

正在从tsv文件中读取字符串并将其放入字符串数组中.正在读取的字符串中包含"\n".

要读取字符串,我使用a StreamReader reader并在\ t中拆分

Jon*_*eet 10

在执行时,您的字符串包含一个反斜杠字符,后跟一个n.它们的编码完全符合它们的要求.如果您确实需要换行符,则不应该在代码中转义反斜杠:

Byte[] bytes = new UTF8Encoding(true).GetBytes("Hello this \n is a test message");
Run Code Online (Sandbox Code Playgroud)

该字符串文字用于\n表示换行符U + 000A.在执行时,字符串不包含反斜杠或n- 它只包含换行符.

但是,您的代码已经很奇怪了,如果您想获得字符串的编码形式,则没有理由通过UTF-8:

byte encodedBytes = codePage.GetBytes("Hello this \n is a test message");
Run Code Online (Sandbox Code Playgroud)