C# Example: Parsing a CSV file and outputting the data - Biz Tech

C# Example: Parsing a CSV file and outputting the data

Listen
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "data.csv";
        List<Person> people = new List<Person>();

        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] fields = line.Split(',');
                    if (fields.Length != 3)
                    {
                        Console.WriteLine("Invalid data: " + line);
                        continue;
                    }

                    string name = fields[0];
                    int age;
                    if (!int.TryParse(fields[1], out age))
                    {
                        Console.WriteLine("Invalid age: " + fields[1]);
                        continue;
                    }

                    string email = fields[2];
                    if (!IsValidEmail(email))
                    {
                        Console.WriteLine("Invalid email address: " + email);
                        continue;
                    }

                    Person person = new Person { Name = name, Age = age, Email = email };
                    people.Add(person);
                }
            }

            foreach (Person person in people)
            {
                Console.WriteLine(person.Name + " " + person.Age + " " + person.Email);
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File not found: " + filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}
 

This example reads a CSV file named “data.csv”, validates the data using string validation methods and a custom IsValidEmail() method, and then outputs the data to the console. The following steps are performed:

  1. Define the Person class with Name, Age, and Email properties.
  2. Define the file path as a variable.
  3. Create an empty List<Person> to hold the parsed data.
  4. Use a StreamReader to read the contents of the CSV file line by line.
  5. Split each line into fields using the Split() method.
  6. Use int.TryParse() to attempt to parse the age field as an integer. If parsing fails, output an error message and continue to the next line using the continue keyword.
  7. Use a custom IsValidEmail() method to check if the email address is valid. If it is not, output an error message and continue to the next line.
  8. Create a new Person object with the parsed data and add it to the List<Person>.
  9. Iterate over the List<Person> and output the Name, Age, and Email properties of each Person object using Console.WriteLine().
  10. Catch any exceptions that may occur during the process and handle them accordingly.