简体   繁体   中英

How to convert string into byte array and write into text file?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM