user3010628
user3010628

Reputation: 29

Writing CSV Parser in C#

I recently started work on a project that searches a CSV file for duplicate entries and present the user the option to delete one or both entries.

Simple enough it would seem, however I am having an issue with the function that actually parses the CSV file into memory.

Here is the code in question...

using System;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
using System.Windows.Forms;


public List<string[]> parseCSV(string path)
{
    List<string[]> parsedData = new List<string[]>();
    string[] fields;

    TextFieldParser parser = null;
    string line = parser.ReadLine();

    try
    {
        /*TextFieldParser*/ parser = new TextFieldParser(@"c:\temp\test.csv");
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");

        while (!parser.EndOfData)
        {
            fields = parser.ReadFields();
            parsedData.Add(fields);

            //Did more stuff here with each field.
        }

        parser.Close();

    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }

   return parsedData;
}

For some reason in VS2017 parseCSV is underlined in red in the function declaration. I can't figure out why this is. I've tried the obvious fixes such as changing the function name from parseCSV to something else but that obviously didn't.

Upvotes: 2

Views: 791

Answers (1)

techhero
techhero

Reputation: 1114

In C# everything is contained in a class, you can't just declare a method within a namespace directly.

using System;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
using System.Windows.Forms;

class MyLearningOnlyCsvParser {

  public List<Customer_Data> parseCSV(string path)
  {
    List<Customer_Data> parsedData = new List<Customer_Data>();
    string[] fields;

    TextFieldParser parser = null;
    string line = parser.ReadLine();

    try
    {
        /*TextFieldParser*/ parser = new TextFieldParser(@"c:\temp\test.csv");
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");

        while (!parser.EndOfData)
        {
            fields = parser.ReadFields();

            // assume the CSV is always with  11 columns
            if(fields.length == 11) {
                Customer_Data newData = new Customer_Data();
                newData.name = fields[0];
                newData.company = fields[1];
                // assign to the rest of the customer data properties with each fields
                parsedData.Add(newData);
            }
            else {
                // error handling of not well formed CSV
            }

        }

        parser.Close();

    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }

   return parsedData;
  }
}

Upvotes: 2

Related Questions