1

There is a question regarding the encoding as in What is character encoding and why should I bother with it. However, I still confuse with the encoding for the Windows system and file.

As I am working C# program on Visual Studio 2017, may I know how to convert the string that is input in the textbox to byte array and write it into a text file?

I am not writing the text to file is because I need the bytes value of the string as compression. For example:

Input : hello world

Bytes array that write to file: 罴讵8?瘈

Thank you for your time!

User233100
  • 49
  • 2
  • 5
  • 1
    Why don't you write the text into the file, instead of the byte array? – Rui Jarimba Nov 01 '18 at 15:58
  • @RuiJarimba Because I need the bytes for other conversion – User233100 Nov 01 '18 at 16:01
  • Your last comment is not understandable. What do you **really** mean when saying "_I need the bytes for other conversion_"? Please explain more in detail. It is probably also a good idea to add an example of a short text and how the byte values should look like in the file.( Edit and improve your question, don't write a comment here.) Because, right now (and probably also in the end), the answer to your question here would _still_ be: Just write the text to the file... –  Nov 01 '18 at 16:04
  • `Encoding.UTF8.GetBytes()` will get you the UTF8 bytes, use a different encoding if you need to – pm100 Nov 01 '18 at 16:05
  • (o.O)??? `趟%觍` are not byte values (a byte has a numerical value between 0 and 255). These are just Chinese characters. Are you asking how to translate English to Chinese? Because if so, this is not about text encoding or byte values/arrays at all. You would need a language translation software with an English->Chinese dictionary to do that... –  Nov 01 '18 at 16:39
  • @elgonzo that is the content of file that shown in Notepad – User233100 Nov 01 '18 at 16:56

1 Answers1

2

Convert to UTF-8 byte array

var byteArray = System.Text.Encoding.UTF8.GetBytes(mystring);

Convert to UTF-8 string

var utf8string = System.Text.Encoding.UTF8.GetString(byteArray);

Write UTF-8 byte array to file

System.IO.File.WriteAllBytes("from-bytearray.txt", byteArray);

Write string to file

System.IO.File.WriteAllText("from-string.txt", utf8string, Encoding.UTF8);
Luthfi
  • 478
  • 1
  • 3
  • 16
  • I have try this way but the output be like N層? . As it is different from the source I refer to, therefore, i wonder about whether is it encoding issue. – User233100 Nov 01 '18 at 16:55