如何将.CSV文件读入类的数组(C#)

时间:2015-07-01 15:47:33

标签: c# arrays csv

我试图将.csv文件中的3个值拉入名为PizzaOrder的类数组中。 .csv文件是使用相同的程序创建的。我在弄清楚如何将.csv中的值插入到PizzaOrder数组中时遇到了问题。

以下是目前表单的代码:

 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();
        }
    }
}

PizzaOrder类按顺序接受int,sting和decimal。 来自.csv的信息需要这样添加。

任何信息和/指导都将非常感谢!谢谢!

3 个答案:

答案 0 :(得分:1)

您需要创建一个新的PizzaOrder对象来执行此操作。除此之外,您还需要转换为正确的数据类型。以下是示例代码:

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

除此之外,您还应该看一些编码标准。局部变量通常不是大写的。列表可能比数组更好,因为您不知道不同的CSV文件将有多少条目。

答案 1 :(得分:0)

使用File.ReadAllLines()读取文件,并使用String.Split()和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();

答案 2 :(得分:0)

除了oppassum的回答之外,在用逗号分割每一行之前,似乎你没有按行拆分你的csv。

        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...
        }