Search code examples
validationfieldmaxlengthfilehelpers

Filehelpers Field max length


I'm working with Filehelpers and imported a csv File. Everything works fine, but now I want to validate the length of the imported Fields.

[DelimitedRecord(";")]
public class ImportFile
{
    public string Name;
    public string NameSurname;
}

Is there a possible way, that I can create an attribute "MaxLength" which split the Input String or Throw an Exception, if the InputString is bigger than my MaxLength Attribut? The only thing I found was the FieldFlixedLength, but thats only the Split, the Inputfile in fields.


Solution

  • You can implement an AfterRead event as follows:

    [DelimitedRecord(";")]
    public class ImportRecord : INotifyRead<ImportRecord>
    {
        public string Name;         
        public string NameSurname;
    
        public void BeforeRead(BeforeReadEventArgs<ImportRecord> e)
        {
        }
    
        public void AfterRead(AfterReadEventArgs<ImportRecord> e)
        {
            if (e.Record.Name.Length > 20)
                throw new Exception("Line " + e.LineNumber + ": First name is too long");
    
            if (e.Record.NameSurname.Length > 20)
                throw new Exception("Line " + e.LineNumber + ": Surname name is too long");
        }
    
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var engine = new FileHelperEngine<ImportRecord>();
            engine.ErrorMode = ErrorMode.SaveAndContinue;
    
            string fileAsString = "Firstname;SurnameIsAVeryLongName" + Environment.NewLine
                                + "FirstName;SurnameIsShort";
    
            ImportRecord[] validRecords = engine.ReadString(fileAsString);
    
            Console.ForegroundColor = ConsoleColor.Red;
            foreach (ErrorInfo error in engine.ErrorManager.Errors)
            {
                Console.WriteLine(error.ExceptionInfo.Message);
            }
    
            Console.ForegroundColor = ConsoleColor.White;            
            foreach (ImportRecord validRecord in validRecords)
            {
                Console.WriteLine(String.Format("Successfully read record: {0} {1}", validRecord.Name, validRecord.NameSurname));
            }
    
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
    }