Search code examples
c#asp.net-coreerror-handlingasp.net-core-2.0fileparsing

Net Core Error Check File Parser for Missing Text


I wrote a file parser utilizing this method.

Sample Text:

1,Joe,CA,58,2
2,Matt,TX,63,5

-

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ParseTest
{
    public class Customer
    {

        public class CustomerData
        {
            // These are the column names in PlatypusN.csv:
            public int CustomerId { get; set; }
            public string CustomerName { get; set; }
            public string CustomerState { get; set; }
            public int ProductId { get; set; }
            public int QuantityBought { get; set; }
        }

        public List<CustomerData> GetCustomer(string filename)
        {
            List<CustomerData> customerdata = new List<CustomerData>();
            string CustomerBase = filename;
            String fileToLoad = String.Format(CustomerBase);

            using (StreamReader r = new StreamReader(fileToLoad))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    // Skip the column names row
                    if (parts[0] == "id") continue;
                    CustomerData dbp = new CustomerData();
                    dbp.CustomerId = Convert.ToInt32(parts[0]);
                    dbp.CustomerName = parts[1];
                    dbp.CustomerState = parts[2];
                    dbp.ProductId = Convert.ToInt32(parts[3]);
                    dbp.QuantityBought = Convert.ToInt32(parts[4]);
                    customerdata.Add(dbp);
                }
            }
            return customerdata;
        }
    }
}

Main Method to Test:

    static void Main()
    {
        Customer customer = new Customer();
        string filename = @"C:\Users\Desktop\Parsefile\sample.txt";

        var test = customer.GetCustomer(filename);
        Console.ReadKey();
    }

Now what happens in the situation, if the sample file contains less data in one line

Sample Text:

1,Joe,CA,58   // missing one number
2,Matt,TX,63,5

Error is the following: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

dbp.QuantityBought = Convert.ToInt32(parts[4]);

What would be cleanest way to resolve this, I do not want to utilize inefficient code like this?

if (parts.Length - 1 >= 1)
dbp.CustomerName = parts[1];
.....
if (parts.Length - 1 >= 4)
dbp.QuantityBought = Convert.ToInt32(parts[4]);

Solution

  • Just catch the exception to ignore the line and continue parsing :

    while ((line = r.ReadLine()) != null)
    {
        try
        {
            string[] parts = line.Split(',');
            // Skip the column names row
            if (parts[0] == "id") continue;
    
            CustomerModel dbp = new CustomerModel
            {
                CustomerId = Convert.ToInt32(parts[0]),
                CustomerName = parts[1],
                CustomerState = parts[2],
                ProductId = Convert.ToInt32(parts[3]),
                QuantityBought = Convert.ToInt32(parts[4])
            };
    
            allFileCustomerData.Add(dbp);
        }
        catch (FormatException ex)
        {
    
        }
        catch (Exception ex)
        {
            throw;
        }
    }