C # '\ n' stored in different bytes than expected

If I save this line in a text file,

Hi, this \ n is a test message

The \ n character is saved as HEX [5C 6E] I would like it to be saved as [0A].

I believe this is an encoding problem?

I use;

// 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); 

All this is in the FileStream area and uses fs.Write to write encoded bytes to the file.

I tried using \ r \ n but had the same result.

Any suggestions?

Thanks!

EDIT

The string is read from the tsv file and placed in an array of strings. The read line has "\ n" in it.

To read a line, I use StreamReader reader and split into \ t

+5
source share
1 answer

At runtime, your string contains a backslash character followed by n . They are encoded exactly as they should be. If you really need a newline character, you should not avoid backslash in your code:

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

This string literal uses \n to represent U + 000A, a newline character. At run time, the string will not contain a backslash or n - it will contain only the string.

However, your code is already odd, if you want to get the encoded string form, there is no reason to go through UTF-8:

 byte encodedBytes = codePage.GetBytes("Hello this \n is a test message"); 
+10
source

Source: https://habr.com/ru/post/1261562/


All Articles