c# convert byte to string and write to txt file
21,686
Solution 1
Starting from bytes:
byte[] b = new byte[255];
string s = Encoding.UTF8.GetString(b);
File.WriteAllText("myFile.txt", s);
and if you start from string:
string x = "255";
byte[] y = Encoding.UTF8.GetBytes(x);
File.WriteAllBytes("myFile2.txt", y);
Solution 2
No need to convert to string. You can just use File.WriteAllBytes
File.WriteAllBytes(@"c:\folder\file.txt", byteArray);
Author by
redfrogsbinary
Updated on November 22, 2020Comments
-
redfrogsbinary over 3 years
How can i convert for example
byte[] b = new byte[1]; b[1]=255
to string ? I need a string variable with the value "255"string text= "255";
and then store it in a text file? -
Jesse Webb over 11 yearsThat will not produce the string
"255"
, it will return the UTF8 character which the byte value255
represents. -
Gregor Primar over 11 yearsAs @Dave wrote question is not clear. So my point was to show OP how to convert between bytes and string and write result to file. I am sure this is all he needs in this case.
-
redfrogsbinary over 11 yearsno i am sorry i didn't mean that. I need a byte b=255; to produce a string text="255";
-
redfrogsbinary over 11 yearsBut what if I wanted a string before writing the txt file?
-
Gregor Primar over 11 yearsWell this is not a problem if you want just that: byte bValue = 255; string sValue = bValue.ToString();
-
redfrogsbinary over 11 yearsAnd what if bValue is an array? byte bValue[] I guess bValue[k].ToString();
-
Gregor Primar over 11 yearsThis is also no problem. Just use specific index, here is sample: byte[] bValue = new byte[] { 255 }; string sValue = bValue[0].ToString();