Search code examples
c#asp.netjsonfile-iostreamreader

Reading content from a file stream c#


I have a web api service that accepts file uploads. The content of the file is a small JSON string like the following:

{ "name":"John", "age":31, "city":"New York" }

How do I get the file content while it is a stream instead of having to save the stream as a file on the web server and then open the file?

The following is my snippet:

byte[] fileData = null;
using(var binaryReader = new BinaryReader(httpRequest.Files[0].InputStream))
{
      fileData = binaryReader.ReadBytes(httpRequest.Files[0].ContentLength);
}

I'm using the 4.0 .NET Framework


Solution

  • You can use a StreamReader class. Try this code:

    using (var reader = new StreamReader(httpRequest.Files[0].InputStream))
    {
        var content = reader.ReadToEnd();
        var json = JObject.Parse(content);
        var name = json["name"];
    }
    

    Another option is to create a class for your json (manually or by http://json2csharp.com/):

    public class Person
    {
        public string name { get; set; }
        public int age { get; set; }
        public string city { get; set; }
    }
    

    Then change your code to this:

    using (var reader = new StreamReader(httpRequest.Files[0].InputStream))
    {
        var content = reader.ReadToEnd();
        var person = JsonConvert.DeserializeObject<Person>(content);
        var name = person.name;
    }