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);
Share:
21,686
redfrogsbinary
Author by

redfrogsbinary

Updated on November 22, 2020

Comments

  • redfrogsbinary
    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
    Jesse Webb over 11 years
    That will not produce the string "255", it will return the UTF8 character which the byte value 255 represents.
  • Gregor Primar
    Gregor Primar over 11 years
    As @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
    redfrogsbinary over 11 years
    no i am sorry i didn't mean that. I need a byte b=255; to produce a string text="255";
  • redfrogsbinary
    redfrogsbinary over 11 years
    But what if I wanted a string before writing the txt file?
  • Gregor Primar
    Gregor Primar over 11 years
    Well this is not a problem if you want just that: byte bValue = 255; string sValue = bValue.ToString();
  • redfrogsbinary
    redfrogsbinary over 11 years
    And what if bValue is an array? byte bValue[] I guess bValue[k].ToString();
  • Gregor Primar
    Gregor Primar over 11 years
    This is also no problem. Just use specific index, here is sample: byte[] bValue = new byte[] { 255 }; string sValue = bValue[0].ToString();