CodeGo.net>如何处理与CsvHelper解析空列?

我有一个CSV文件,我正在尝试解析它,但是在int数据类型列上收到以下错误.在该文件中,我正在为此列传递空白或空值.

[AutoMap(typeof(Test))]
[FileEntity("Test")]
public class TestFileEntity : BaseFileEntity
{
    [CsvFileColumn(1)]
    public int TestId { get; set; }
}

public IEnumerable<BaseFileEntity> Parse(Stream masterData, Type entityType, out IEnumerable<MasterDataFileParserError> errors)
{
    var list = new List<BaseFileEntity>();
    var errorList = new List<MasterDataFileParserError>();

    try
    {
        using (var reader = new StreamReader(masterData))
        {
            var parser = new CsvReader(reader, new CsvHelper.Configuration.Configuration
            {
                HasHeaderRecord = true,
                HeaderValidated = null,
                MissingFieldFound = null
            });

            list.AddRange(parser.GetRecords(entityType).Cast<BaseFileEntity>());
        }
    }
    catch (Exception ex)
    {
        if (ex.Data == null || ex.Data.Count == 0)
        {
            errorList.Add(new MasterDataFileParserError
            {
                Error = ex.Message,
                Description = ex.ToString()
            });
        }
        else
        {
            foreach (var key in ex.Data.Keys)
            {
                errorList.Add(new MasterDataFileParserError
                {
                    Error = ex.Message,
                    Description = $"{key}: {ex.Data[key]}"
                });
            }
        }
    }

    errors = errorList;

    return list;
}

此行的异常:list.AddRange(parser.GetRecords(entityType).Cast< BaseFileEntity>());

错误:

An error has occurred while parsing ‘xyz.csv’ file for ‘Test’ entity:
‘[{“Error”:”The conversion cannot be performed.\r\n Text: ”\r\n
MemberType: System.Int32\r\n TypeConverter:
‘CsvHelper.TypeConversion.Int32Converter'”,”Description”:”CsvHelper.TypeConversion.TypeConverterException:
The conversion cannot be performed.\r\n Text: ”\r\n MemberType:
System.Int32\r\n TypeConverter:
‘CsvHelper.TypeConversion.Int32Converter’\r\n at
CsvHelper.Configuration.Configuration.<>c.<.ctor>b__148_4(CsvHelperException
exception)\r\n at
CsvHelper.CsvReader.d__65.MoveNext()\r\n at
System.Linq.Enumerable.d__341.MoveNext()\r\n at
System.Collections.Generic.List
1.AddEnumerable(IEnumerable1
enumerable)\r\n at
System.Collections.Generic.List
1.InsertRange(Int32 index,
IEnumerable1 collection)\r\n at
Nec.Stanchion.Business.MasterDataFiles.Handling.MasterDataFileParser.Parse(Stream
masterData, Type entityType, IEnumerable
1& errors) in xyz.cs
file”}]’.

原因很清楚,空白或空字符串与int数据类型不兼容,因此必须有某种方法允许int数据类型列值为空或null值.

CsvHelper版本= 6.0.0.0

解决方法:

我在当前项目中使用的是CsvHelper 6.1.0,只是测试了一个与您类似的用例,csv文件中的int字段为空白,并且没有问题.这是我正在使用的代码,希望对您有所帮助:

        CsvReader csv = new CsvReader(new StreamReader(file.OpenReadStream()));
        csv.Configuration.RegisterClassMap<PessoaCSVMap>();
        csv.Configuration.Delimiter = ";";
        csv.Configuration.HeaderValidated = null;
        csv.Configuration.MissingFieldFound = null;
        List<Pessoas> pessoas = csv.GetRecords<Pessoas>().ToList();
public sealed class PessoaCSVMap : ClassMap<Pessoas>
{
    public PessoaCSVMap()
    {
        Map(m => m.Nome).Name("Nome", "Name");
        ... etc
    }
}
上一篇:使用CSVhelper C#合并具有不同标题的CSV文件


下一篇:C#CsvHelper.ValidationException – 为什么?