Reading CSV file and storing values into an array

后端 未结 19 1444
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

19条回答
  •  孤街浪徒
    2020-11-22 07:00

    I am just student working on my master's thesis, but this is the way I solved it and it worked well for me. First you select your file from directory (only in csv format) and then you put the data into the lists.

    List t = new List();
    List SensorI = new List();
    List SensorII = new List();
    List SensorIII = new List();
    using (OpenFileDialog dialog = new OpenFileDialog())
    {
        try
        {
            dialog.Filter = "csv files (*.csv)|*.csv";
            dialog.Multiselect = false;
            dialog.InitialDirectory = ".";
            dialog.Title = "Select file (only in csv format)";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var fs = File.ReadAllLines(dialog.FileName).Select(a => a.Split(';'));
                int counter = 0;
                foreach (var line in fs)
                {
                    counter++;
                    if (counter > 2)    // Skip first two headder lines
                    {
                        this.t.Add(float.Parse(line[0]));
                        this.SensorI.Add(float.Parse(line[1]));
                        this.SensorII.Add(float.Parse(line[2]));
                        this.SensorIII.Add(float.Parse(line[3]));
                    }
                }
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(
                "Error while opening the file.\n" + exc.Message, 
                this.Text, 
                MessageBoxButtons.OK, 
                MessageBoxIcon.Error
            );
        }
    }
    

提交回复
热议问题