Curriculum
StringReader is a class in C# that allows you to read text data from a string. It is useful when you need to read formatted text that is stored in memory, rather than reading from a file or a network socket.
Here’s an example of using StringReader to read a CSV file as a string and parse it into a list of objects:
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
// CSV data as a string
string csvData = "Name, Age, GendernJohn, 30, MalenJane, 25, Female";
// Create a StringReader object to read the CSV data
using (StringReader stringReader = new StringReader(csvData))
{
// Read the header row of the CSV data
string header = stringReader.ReadLine();
// Split the header row into columns
string[] columns = header.Split(',');
// Create a list to store the parsed objects
List<Person> people = new List<Person>();
// Read the remaining rows of the CSV data
string line;
while ((line = stringReader.ReadLine()) != null)
{
// Split the row into values
string[] values = line.Split(',');
// Create a Person object from the values
Person person = new Person();
person.Name = values[0];
person.Age = int.Parse(values[1]);
person.Gender = values[2].Trim();
// Add the person to the list
people.Add(person);
}
// Display the parsed objects
foreach (Person person in people)
{
Console.WriteLine("{0} ({1}, {2})", person.Name, person.Age, person.Gender);
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
}
In this example, we first create a string that contains CSV data. We then create a StringReader object to read the CSV data, and use it to read the header row and the remaining rows of data. We split each row into values using the Split method, and create a Person object from the values. Finally, we add the Person object to a list of parsed objects, and display the list.
It’s important to note that StringReader can be used with any class that implements the TextReader abstract class, allowing you to read formatted text in various formats such as JSON or XML. Additionally, you should always dispose of the StringReader object once you’re finished using it, which is achieved by calling the Dispose method or wrapping it in a using statement.