Reading CSV files using C#

后端 未结 12 2492
野的像风
野的像风 2020-11-21 22:49

I\'m writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For ex

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 23:48

    Sometimes using libraries are cool when you do not want to reinvent the wheel, but in this case one can do the same job with fewer lines of code and easier to read compared to using libraries. Here is a different approach which I find very easy to use.

    1. In this example, I use StreamReader to read the file
    2. Regex to detect the delimiter from each line(s).
    3. An array to collect the columns from index 0 to n

    using (StreamReader reader = new StreamReader(fileName))
        {
            string line; 
    
            while ((line = reader.ReadLine()) != null)
            {
                //Define pattern
                Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
    
                //Separating columns to array
                string[] X = CSVParser.Split(line);
    
                /* Do something with X */
            }
        }
    

提交回复
热议问题