Reading CSV files using C#

后端 未结 12 2523
野的像风
野的像风 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:29

    I'd highly suggest using CsvHelper.

    Here's a quick example:

    public class csvExampleClass
    {
        public string Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
    }
    
    var items = DeserializeCsvFile>( csvText );
    
    public static List DeserializeCsvFile(string text)
    {
        CsvReader csv = new CsvReader( new StringReader( text ) );
        csv.Configuration.Delimiter = ",";
        csv.Configuration.HeaderValidated = null;
        csv.Configuration.MissingFieldFound = null;
        return (List)csv.GetRecords();
    }
    

    Full documentation can be found at: https://joshclose.github.io/CsvHelper

提交回复
热议问题