Using the FileHelper Library Is there a way to get an exception if the record does not have expected number of delimiters in a line?
And another question is there is there a way to get an exception if a particular field for example Name is more than expected length?
If i set name to be maxLength 30 i get an exception if its is above 30.
Or a field is simply not equal to expected length?
It is the Default FileHelpers behavior to throw exceptions if there are not enough/too many fields in the line, so there is no need to do anything special to get it:
[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);
Will result in
FileHelpers.FileHelpersException: Line: 1 Column: 4. Delimiter ',' not found after field 'k__BackingField' (the record has less fields, the delimiter is wrong or the next field must be marked as optional). at FileHelpers.DelimitedField.BasicExtractString(LineInfo line) at FileHelpers.DelimitedField.ExtractFieldString(LineInfo line) at FileHelpers.FieldBase.ExtractFieldValue(LineInfo line) at FileHelpers.RecordOperations.StringToRecord(Object record, LineInfo line, Object[] values) at FileHelpers.FileHelperEngine`1.ReadStreamAsList(TextReader reader, Int32 maxRecords, DataTable dt)
As far as I can see FileHelpers doesn't support standard DataAnnotations out of the box (or it can actually support it but it doesn't work due to https://github.com/dotnet/standard/issues/450), so you will probably have to add validation manually
So, you install https://www.nuget.org/packages/System.ComponentModel.Annotations/4.4.0
And then by adding [StringLength(maximumLength: 5)]
to the SomeString
property on the model
[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}";
}
With
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);
}
}
You will get the following output
Not valid
The field SomeString must be a string with a maximum length of 5.