How can I read and parse a semicolon-separated file into objects in C# in a clean and readable way?

1 week ago 16
ARTICLE AD BOX

I’m working with a simple text file containing car data, and I’d like to parse it into strongly typed objects in C#.

The file structure looks like this:

Brand;Model;FuelType;Year;Price Toyota;Corolla;Petrol;2018;15000 Ford;Focus;Diesel;2016;12000

In some cases, multiple records may appear on the same line separated by spaces.

My goal is to keep the code easy to read and maintain, not just make it work.

What would be a clean and understandable way to:

read the file

parse the data

store it in a list of objects

Here is my approach:

using System; using System.Collections.Generic; using System.IO; namespace Assignment { internal class Car { public string Brand { get; set; } public string Model { get; set; } public string FuelType { get; set; } public int Year { get; set; } public int Price { get; set; } public Car(string brand, string model, string fuelType, int year, int price) { Brand = brand; Model = model; FuelType = fuelType; Year = year; Price = price; } public static List<Car> ReadFromFile() { List<Car> cars = new List<Car>(); // Read all lines (first line is header) string[] lines = File.ReadAllLines("cars.txt"); for (int i = 1; i < lines.Length; i++) { // A line may contain multiple records separated by space string[] records = lines[i].Split(' '); for (int j = 0; j < records.Length; j++) { // Each record is separated by semicolon string[] data = records[j].Split(';'); Car car = new Car( data[0], data[1], data[2], int.Parse(data[3]), int.Parse(data[4]) ); cars.Add(car); } } return cars; } } }

You can also take this one step further and keep the file-reading logic separate from the code that works with the parsed objects.

For example, after Car.ReadFromFile() returns a List, you can store that list inside another class responsible for querying or processing the data:

using System; using System.Collections.Generic; namespace Assignment { internal class CarManager { private List<Car> cars; public CarManager() { cars = Car.ReadFromFile(); } public int CountCars() { return cars.Count; } } class Program { static void Main(string[] args) { CarManager manager = new CarManager(); Console.WriteLine("Total cars: " + manager.CountCars()); } } }

How can I improve this code to make it more readable and robust?

Read Entire Article