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!

6
  • 1
    Why don't you write the text into the file, instead of the byte array? Commented Nov 1, 2018 at 15:58
  • @RuiJarimba Because I need the bytes for other conversion Commented Nov 1, 2018 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... Commented Nov 1, 2018 at 16:04
  • Encoding.UTF8.GetBytes(<string>) will get you the UTF8 bytes, use a different encoding if you need to Commented Nov 1, 2018 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... Commented Nov 1, 2018 at 16:39

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.