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:
- Define the
Person
class withName
,Age
, and- Define the file path as a variable.
- Create an empty
List<Person>
to hold the parsed data.- Use a
StreamReader
to read the contents of the CSV file line by line.- Split each line into fields using the
Split()
method.- 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 thecontinue
keyword.- 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.- Create a new
Person
object with the parsed data and add it to theList<Person>
.- Iterate over the
List<Person>
and output theName
,Age
, andPerson
object usingConsole.WriteLine()
.- Catch any exceptions that may occur during the process and handle them accordingly.