I have some C++ code that persists byte values into files via STL strings & text i/o, and am confused about how to do this in C#.
first I convert byte arrays to strings & store each as a row in a text file:
StreamWriter F
loop
{
byte[] B; // array of byte values from 0-255 (but never LF,CR or EOF)
string S = B; // I'd like to do this assignment in C# (encoding? ugh.) (*)
F.WriteLine(S); // and store the byte values into a text file
}
later ... I'd like to reverse the steps and get back the original byte values:
StreamReader F;
loop
{
string S = F.ReadLine(); // read that line back from the file
byte[] B = S; // I'd like to convert back to byte array (*)
}
How do you do those assignments (*) ?
class Encoding
supports what you need, example below assumes that you need to convert string
to byte[]
using UTF8
and vice-versa:
string S = Encoding.UTF8.GetString(B);
byte[] B = Encoding.UTF8.GetBytes(S);
If you need to use other encodings, you can change easily:
Encoding.Unicode
Encoding.ASCII
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With