5

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?

2
  • Admits to confusion..... Commented Nov 21, 2012 at 22:21
  • What's stored in that array? characters? Commented Nov 21, 2012 at 22:21

2 Answers 2

15

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);
Sign up to request clarification or add additional context in comments.

6 Comments

That will not produce the string "255", it will return the UTF8 character which the byte value 255 represents.
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.
no i am sorry i didn't mean that. I need a byte b=255; to produce a string text="255";
Well this is not a problem if you want just that: byte bValue = 255; string sValue = bValue.ToString();
And what if bValue is an array? byte bValue[] I guess bValue[k].ToString();
|
3

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

File.WriteAllBytes(@"c:\folder\file.txt", byteArray);

1 Comment

But what if I wanted a string before writing the txt file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.