如何使用FileHelper库获取定界符数量

问题描述 投票:-1回答:1

使用FileHelper库,如果记录在一行中没有预期的分隔符,是否有办法获取异常?

另外一个问题是,如果某个特定字段(例如名称)超过了预期的长度,是否有办法获得例外?

如果我将名称设置为maxLength 30,则它的值大于30则出现异常。

或者一个字段根本不等于期望的长度?

c# filehelpers file-processing fileparsing
1个回答
0
投票

如果记录中一行中没有预期的分隔符,则获取异常

这是默认的FileHelpers行为,如果该行中没有足够/太多的字段,则引发异常,因此不需要做任何特殊的事情来获得它:

[DelimitedRecord(",")]
public class Test
{
    public int SomeInt { get; set; }
    public string SomeString { get; set; }
    public int SomeInt1 { get; set; }

    public override string ToString() =>
        $"{SomeInt} - {SomeString} - {SomeInt1}";
}


var result = new FileHelperEngine<Test>()
    .ReadString(@"123,That's the string")
    .Single();
Console.WriteLine(result);

将产生结果

FileHelpers.FileHelpersException:行:1列:4.分隔符','不是在字段“ k__BackingField”之后找到(记录较少字段,分隔符错误,或者下一个字段必须标记为可选的)。在FileHelpers.DelimitedField.BasicExtractString(LineInfo行)位于FileHelpers.DelimitedField.ExtractFieldString(LineInfo行)位于FileHelpers.FieldBase.ExtractFieldValue(LineInfo行)位于FileHelpers.RecordOperations.StringToRecord(对象记录,LineInfo行,Object []值)在FileHelpers.FileHelperEngine`1.ReadStreamAsList(TextReader reader,Int32 maxRecords,DataTable dt)

如果特定字段(例如名称)超过预期长度,是否可以获取异常

据我所见,FileHelpers不支持现成的标准DataAnnotations(或者它实际上可以支持它,但是由于https://github.com/dotnet/standard/issues/450而无法使用,所以您可能必须手动添加验证]

因此,您安装了https://www.nuget.org/packages/System.ComponentModel.Annotations/4.4.0

然后通过将[StringLength(maximumLength: 5)]添加到模型的SomeString属性中>>

[DelimitedRecord(",")]
public class Test
{
    public int SomeInt { get; set; }
    [StringLength(maximumLength: 5)]
    public string SomeString { get; set; }
    public int SomeInt1 { get; set; }

    public override string ToString() =>
        $"{SomeInt} - {SomeString} - {SomeInt1}";
}

使用

var result = new FileHelperEngine<Test>()
    .ReadString(@"123,That's the string, 456")
    .Single();
Console.WriteLine(result);

var context = new ValidationContext(result, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(result, context, results, validateAllProperties: true);
if (!isValid)
{
    Console.WriteLine("Not valid");
    foreach (var validationResult in results)
    {
        Console.WriteLine(validationResult.ErrorMessage);
    }
} 

您将获得以下输出

无效

字段SomeString必须是最大长度为5的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.