2

I have JSON in a text file, and I read the bytes of the file into an array:

byte[] data = File.ReadAllBytes(filename);

Now, I want to get a string that contains the JSON data that was in the original file, but I only have the data byte array available.

Any help would be appreciated.

Thanks.

3 Answers 3

6

What about using File.ReadAllText instead?

Anyway, you can convert a Byte[] to a String using Encoding.UTF8.GetString(data)

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way to directly converting bytes[] to JSON String instead of converting to string and then JSON String?
4

You need to setup an encoding and then convert the bytes to a string, like so:

System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(myByteArray );

Although, if your goal is simply to read the JSON into a string, then everyone else's answer is right. Just use File.ReadAllText

Comments

1

Why not use File.ReadAllText instead? That'll give you a string off the bat.

2 Comments

Because the data[] stream is the only thing available to me at the point where I need to restore the JSON string
Fair enough, in that case, Simon or Icemanind's suggestion for conversion will do the job :)

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.