0

I want to read a file data.json and convert it to a string.

My code is this one:

String json = null;

using (StreamReader sr = new StreamReader("data.json"))
{
     json = sr.ReadToEnd();
}

but Visual Studio tells me that StreamReader does not expect a String as constructor argument.

How can I tell StreamReader that I want to read the file data.json?

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
nix86
  • 2,837
  • 11
  • 36
  • 69

1 Answers1

3

Actually StreamReader supports constructor which accepts file path for most platforms, but not all. But anyway - simply use File.ReadAllText:

string json = File.ReadAllText("data.json");

It creates StreamReader internally (link to source):

using (var sr = new StreamReader(path, encoding))
    return sr.ReadToEnd();

UPDATE: You can always pass stream to StreamReader. Use FileStream to open stream for reading file, and then pass it to StreamReader:

string json = null;
using (var stream = new FileStream("data.json", FileMode.Open))
using (var reader = new StreamReader(stream))
    json = reader.ReadToEnd();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459