C# – Convert output of a Web request into an object list

|
| By Webner

WebRequest gives response in the form of Stream. In order to use it further in the form of c# object, I have used below code:

Sample code :

WebRequest requestHttp = WebRequest.Create(reqURL);
using(WebResponse responseHttpRequest = requestHttp.GetResponse()) {
    Stream responseStream = responseHttpRequest.GetResponseStream();;
    StreamReader reader = new StreamReader(responseStream);
    string text = reader.ReadToEnd();
    using(TextReader sr = new StringReader(text)) {
        var csv = new CsvReader(sr);
        var records = csv.GetRecords < CsvFile > ();
        foreach(CsvFile cs in records) {
            csvfile.Id = cs.Id;
            csvfile.Success = cs.Success;
        }
    }
}

public class CsvFile {
    public string Id {
        get;
        set;
    }
    public string Success {
        get;
        set;
    }
}

Above code will convert the response stream into a List, which can be used in any way throughout the project.

Leave a Reply

Your email address will not be published. Required fields are marked *