Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert byte to string and write to txt file

Tags:

string

c#

byte

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?

like image 368
redfrogsbinary Avatar asked Nov 21 '12 22:11

redfrogsbinary


2 Answers

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);
like image 120
Gregor Primar Avatar answered Oct 18 '22 00:10

Gregor Primar


No need to convert to string. You can just use File.WriteAllBytes

File.WriteAllBytes(@"c:\folder\file.txt", byteArray);
like image 34
Bill Tarbell Avatar answered Oct 18 '22 02:10

Bill Tarbell