Reading, splitting, and displaying a multiline CSV file in C#

前端 未结 2 958
遥遥无期
遥遥无期 2021-02-10 14:14

All,

I\'m trying to write a testbed program that will eventually allow me to take a CSV .txt file and put its contents into a SQLite database file. There are hundreds o

2条回答
  •  面向向阳花
    2021-02-10 14:45

    This is how I would do it:

    First, define a class to hold the output of your file:

    public class MyData
    {
        public MyData() { }
    
        public MyData(string[] values)
        {
            Time = new DateTime(long.Parse(values[0]));
            HlState = int.Parse(values[1]);
            HLX = double.Parse(values[2]);
            HLY = double.Parse(values[3]);
            HLZ = double.Parse(values[4]);
        }
    
        public DateTime Time { get; set; }
        public int HLState { get; set; }
        public double HLX { get; set; }
        public double HLY { get; set; }
        public double HLZ { get; set; }
    }
    

    Then modify you button event to populate a list of those objects

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document";
            dlg.DefaultExt = ".txt";
            dlg.Filter = "Text Documents (.txt)|*.txt";
    
            if (dlg.ShowDialog() == true)
            {
                fileName = dlg.FileName;
                OutputConsole.Text = " ";
                OutputConsole.Text = fileName;
    
                var output = new List();
    
                try
                {
                    // First line skipped as we do not need headers.
                    foreach (var line in File.ReadAllLines(filename).Skip(1))
                    {
                        output.Add(new MyData(line.Split(",")));
                    }
    
                    OutputConsole.Text = string.Format("{0} lines read.", output.Lenght);
                }
                catch (System.IO.IOException ex)
                {
                    //let user know there was an error reading file
                }
    
                // Do something with output
    
            }
        }
    

    Now you have a collection output of objects each with a strong typed access to your values, which should easily populate into a DB

提交回复
热议问题