RAV4RUNR
RAV4RUNR

Reputation: 17

How to read a .CSV file into an array of a class (C#)

I am trying to pull 3 values from a .csv file into an array of class called PizzaOrder. The .csv file was created using the same program. I am having problems figuring out how to insert the values from the .csv into the array of PizzaOrder.

Here is the code of the form so far:

 public partial class Form1 : Form
{
    PizzaOrder[] pizzaArray = new PizzaOrder[4];

    PizzaOrder[] ReadPizzaArray = new PizzaOrder[4];

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //this is just creating the values and inserting into the array
        PizzaOrder p1 = new PizzaOrder(12, "Pepperoni", 14.88m);
        PizzaOrder p2 = new PizzaOrder(15, "Mushrooms", 15.69m);
        PizzaOrder p3 = new PizzaOrder(13, "Bacon", 15.33m);
        PizzaOrder p4 = new PizzaOrder(16, "Olives", 17.47m);

        pizzaArray[0] = p1;
        pizzaArray[1] = p2;
        pizzaArray[2] = p3;
        pizzaArray[3] = p4;
    }

    private void btnDisplay_Click(object sender, EventArgs e)
    {
       //this is just displaying the contents of the array in a listbox
        lstOrders.Items.Clear();

        for(int loop = 0; loop < pizzaArray.Length; loop++)
        {
            lstOrders.Items.Add(pizzaArray[loop].ShowOrder());
        }
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
     //this is where the .csv file is being created and saved to
        StreamWriter SavePizza = new StreamWriter("PizzaFile.csv", true);
        try
        {

            for (int loop = 0; loop < pizzaArray.Length; loop++)
            {
                SavePizza.Write(pizzaArray[loop].ShowOrder()+ Environment.NewLine);
            }
        }
        catch(System.Exception)
        {
            MessageBox.Show("A file write error has occured...", "File Error");
        }
        finally
        {
            SavePizza.Close();   
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //this is where I am attempting to read from the .csv
        StreamReader ReadPizza = new StreamReader(File.OpenRead("PizzaFile.csv"));
        try
        {

            string input = ReadPizza.ReadToEnd();
            string[] PizzaRead = input.Split(',');

            for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
            {
             //this is where I'm trying to insert from the .csv into the array again, where the problem is
                ReadPizzaArray[loop2] = (PizzaRead[0], PizzaRead[1], PizzaRead[2]);

            }

        }
        catch(System.Exception)
        {
            MessageBox.Show("An error occured during the file read...","File Read Error");
        }
        finally
        {
            ReadPizza.Close();
        }
    }
}

The PizzaOrder class accepts an int, sting, and decimal in that order. The information from the .csv needs to be added as such.

Any information and/guidance would be most appreciated! Thanks!

Upvotes: 0

Views: 249

Answers (3)

heltonbiker
heltonbiker

Reputation: 27575

Read the file with File.ReadAllLines(), and use String.Split() and String.Trim():

var lines = File.ReadAllLines("PizzaFile.csv")
List<PizzaOrder> orders = new List<PizzaOrder>();

foreach (var line in lines)
{
    var fields = line.Split(',');
    PizzaOrder order = new PizzaOrder()
    {
        Id = Convert.ToInt32(fields[0].Trim());
        Type = fields[1].Trim();
        // etc.
    }
}

var result = orders.ToArray();

Upvotes: 0

tzachs
tzachs

Reputation: 5019

In addition to oppassum's answer, it seems like you didn't split your csv by lines before splitting each line by commas.

        string input = ReadPizza.ReadToEnd();
        string[] lines = input.Split(new[] { Environment.NewLine}, StringSplitOptions.RemoveEmptryEntries);
        foreach (string line in lines)
        {
           string[] PizzaRead = line.Split(',');
           //Insert oppassum's answer here...
        }

Upvotes: 0

oppassum
oppassum

Reputation: 1765

You will want to create a new PizzaOrder object to do this. Along with that, you will need to convert to the proper data types. Here is example code:

for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)
        {
            ReadPizzaArray[loop2] = new PizzaOrder(Convert.ToInt32(PizzaRead[0]), PizzaRead[1].ToString(), Convert.ToDecimal(PizzaRead[3]));
        }

Along with this, you should take a look at some coding standards. local variables are usually not capitalized. A List would likely work better than an array, as you don't know how many entries there will be for different CSV files.

Upvotes: 1

Related Questions