【问题标题】:CSVHelper mandatory fieldsCSVHelper 必填字段
【发布时间】:2014-11-03 11:06:17
【问题描述】:

解析 csv 文件时,如何定义特定字段为必填字段。本质上,我想确保给定字段永远不会为空,如果是,那么我希望抛出异常。这是映射类:

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
    }
}

及用法:

List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
    var reader = new CsvReader(sr);
    reader.Configuration.RegisterClassMap<DataMapper>();
    data = reader.GetRecords<DataType>().ToList();
}

目前我只是查看数据列表中的结果如下:

var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
    //handle
}

我无法在 CSVHelper 文档中找到内置功能。我错过了什么吗?

【问题讨论】:

    标签: c# csvhelper


    【解决方案1】:

    我可能会使用ConvertUsing 扩展来做到这一点:

    public sealed class DataMapper : CsvClassMap<DataType>
    {
        public DataMapper()
        {
            Map(m => m.Field1).Name("FirstField");
            Map(m => m.Field2).Name("SecondField");
            Map(m => m.Field3).ConvertUsing(row =>
            {
                if(string.IsNullOrEmpty(row.GetField<string>("ThirdField")))
                    throw new Exception("Oops, ThirdField is empty!");
                return row.GetField<string>("ThirdField");
            });
        }
    }
    

    【讨论】:

    • 'Get' 方法已被移除,并在新版本的库中被 'GetField' 方法取代
    • @HakamFostok 谢谢,你应该在里面修好它:)
    【解决方案2】:

    这是一个扩展 API 的解决方案:

    public static class CsvHelperExtensions
    {
        public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
        {
            return map.Name(columnName).ConvertUsing(row =>
            {
                if (string.IsNullOrEmpty(row.GetField(columnName)))
                    throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
                return row.GetField<T>(columnName);
            });
        }
    }
    

    用法:

    public CsvPersonMap()
    {
        Map(m => m.FirstName).Required<string>("First");
        Map(m => m.LastName).Name("Last");
        Map(m => m.MiddleName).Required<string>("Middle");
    }
    

    【讨论】:

      【解决方案3】:

      开发者现在添加了一个验证方法:https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation

      使用它来验证非空或空字符串:

      Map(m =&gt; m.Id).Validate(field =&gt; !string.IsNullOrEmpty(field));

      https://github.com/JoshClose/CsvHelper/issues/556

      【讨论】:

        【解决方案4】:

        As suggested by the creator of CsvHelper here:

        目前,我认为您必须拥有 WillThrowOnMissingField = false 并运行一个循环并检查您的具体情况 必填字段。您可能只需在 初读。

        他的示例代码:

        csv.WillThrowOnMissingField = false;
        var list = new List<MyObject>();
        var headerChecked = false;
        while( csv.Read() )
        {
            if( !headerChecked )
            {
                // check for specific headers
                if( !csv.FieldHeaders.Exists( "MyHeaderName" ) )
                {
                    throw new Exception( "message" );
                }
                headerChecked = true;
            }
        
            list.Add( csv.GetRecord<MyObject>() );
        }
        

        【讨论】:

        • 这仅对检查源文件是否有该列有用。 OP 要求确保该值不为空。
        猜你喜欢
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 2020-03-17
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多