Reading CSV files using C#

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

    To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser or the string.Split method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.

    I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.

    I deserialize my CSV file with the following method:

    public static IEnumerable ReadCsvFileTextFieldParser(string fileFullPath, string delimiter = ";") where T : new()
    {
        if (!File.Exists(fileFullPath))
        {
            return null;
        }
    
        var list = new List();
        var csvFields = GetAllFieldOfClass();
        var fieldDict = new Dictionary();
    
        using (TextFieldParser parser = new TextFieldParser(fileFullPath))
        {
            parser.SetDelimiters(delimiter);
    
            bool headerParsed = false;
    
            while (!parser.EndOfData)
            {
                //Processing row
                string[] rowFields = parser.ReadFields();
                if (!headerParsed)
                {
                    for (int i = 0; i < rowFields.Length; i++)
                    {
                        // First row shall be the header!
                        var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
                        if (csvField != null)
                        {
                            fieldDict.Add(i, csvField);
                        }
                    }
                    headerParsed = true;
                }
                else
                {
                    T newObj = new T();
                    for (int i = 0; i < rowFields.Length; i++)
                    {
                        var csvFied = fieldDict[i];
                        var record = rowFields[i];
    
                        if (csvFied is FieldInfo)
                        {
                            ((FieldInfo)csvFied).SetValue(newObj, record);
                        }
                        else if (csvFied is PropertyInfo)
                        {
                            var pi = (PropertyInfo)csvFied;
                            pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
                        }
                        else
                        {
                            throw new Exception("Unhandled case.");
                        }
                    }
                    if (newObj != null)
                    {
                        list.Add(newObj);
                    }
                }
            }
        }
        return list;
    }
    
    public static IEnumerable GetAllFieldOfClass()
    {
        return
            from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
            where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
            let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
            orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
            select mi;            
    }
    

提交回复
热议问题