Parsing CSV Row To C# Object

With the widespread popularity of Nuget, there is a package for everything in C#. Parsing CSVs are no exception, but this feels like overkill. Parsing a csv, tsv or any value separated file in C# is not complicated and can be done very easily by simply breaking up the string. It takes a little more work when compared to the simplicity of json serialisation, but it is worth the effort. Particularly if you work for an orginazation that requires nuget packages to be reviewed before adding to an internal repository.

For this example, we will use the following CSV file. You can use this class with pretty much any file that has some kind of value separated data. Tabs are a common alternative that you can easily modify to use this example too.

title,description,price,creationDate<br>
"Converting a csv row to class","Use this class as a template to convert a csv row to a C# class",5.99,2019-01-01 00:00:00

The following class has properties based off the title of this CSV file. We want to skip the first row of course, it wont parse anyway as it will throw an exception due to price not being a decimal and creationDate not being a DateTime. By creating a method called TryParseRow, it falls inline with similar methods we have for the core data types in C# like Int, Double, DateTime and Decimal. The only difference is it doesn’t need to have an out property.

public class MyCSVRowClass
{
	public string Title;
	public string Description;
	public decimal Price;
	public DateTime CreationDate;
	
	
	public bool TryParseRow(string filerow)
	{
		try
		{
			var columns = filerow.Split(';');
			if (columns.Count() == 4) //dont accept a row with a different number of columns. It might be a new column at the end and cause no trouble. It may also be in the middle and screw everything up.
			{
				this.Title = columns[0];
				this.Description = columns[1];
				this.Price = Decimal.Parse(columns[2]); //optionally use try parse if you want to load the row even if one of the columns is invalid.
				this.CreationDate = DateTime.Parse(columns[3]);
				return true;
			}
			else
				return false;
		}
		catch (Exception e)
		{
			return false;
		}
	}
}

Using this class is a simple case of calling MyCSVRowClass.TryParseRow(csv row);. If the method returns a negative response, you know there was a parsing error with the line and you can ignore it. You may have a data file with some optional values in which case you may want to use the try parse methods inside the row parsing method. This way the code will continue parsing the line, even if one property is missing or invalid.

For ease of use, you could create a collection class that wraps up the parsing and file reading into one easy process.

public class MyCSVRowCollection
{
	public List<MyCSVRowClass> Rows;
	
	public void LoadFile(string file)
	{
		using{StreamReader file = new System.IO.StreamReader(file)}
		{		
			while((line = file.ReadLine()) != null)  
			{  
				var lineobj = new MyCSVRowClass();
				if(lineobj.TryParseRow(line))
					this.Rows.Add(lineobj);
			}
		}
	}
}

Related Articles

Related Questions

Best File Sync Strategy for High-Latency Remote Office

Hey everyone, We're based in Germany, where we have our main file server (Samba) hosted on Hetzner Cloud, serving about 40 users. Recently, we opened...

Are YouTube Courses Enough to Master Advanced Programming Concepts?

I'm just starting my programming journey and have been following a YouTube course on C from Bro Code. However, I'm wondering if these free...

Trouble Accessing HPE Proliant Gen10 iLO5 from Outside Management VLAN

I've recently set up iLO on an HPE Proliant Gen10 server, and I'm facing an access issue. Both my servers are on the same...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Latest Tools

Scavenger Hunt Team Randomizer

Planning a scavenger hunt and need to split participants into random teams? Whether you're organizing a school activity, a corporate team-building event, or a...

File Hash Generator Online – Get Instant MD5 and SHA-256 Hashes

Whether you are validating downloads, checking for corruption, or comparing files for duplicates, having a fast and secure way to generate file hashes is...

Visual CSS Editor for Modern Glass UI Effects

Modern UI design is all about clean, layered aesthetics, and few styles deliver this better than glassmorphism. If you're designing sleek user interfaces and...

Fast and Accurate Tap BPM Counter – Free Web Tool

Whether you're producing music, DJing live, or just figuring out the tempo of a song, knowing the BPM (beats per minute) can be critical....

Glassmorphism CSS Generator with Live Preview

Glassmorphism is one of the most visually striking design trends in modern UI. Its soft, frosted-glass effect adds depth and elegance to web interfaces,...

Add Custom Speech and Caption Boxes to Any Image Online

Creating comic-style images used to require complex design tools or specialist software. Whether you're making memes, teaching graphics, social media posts or lighthearted content,...

Latest Posts

Latest Questions