FileHelpers: How to skip first and last line reading fixed width text

前端 未结 3 879
无人共我
无人共我 2021-02-19 02:31

Code below is used to read fixed width uploaded file content text file using FileHelpers in ASP .NET MVC2

First and last line lengths are smaller and ReadStream causes e

相关标签:
3条回答
  • 2021-02-19 02:47

    You could use the BeforeReadRecord event to check the format of the line. Set the SkipThisRecord property in the event data if it's the first record. Determining if it's the last record is something of a problem, but you could just check the length or format instead. Of course, that'll prevent you from catching errors caused by malformed records.

    Another possibility is to load the entire file into memory using File.ReadAllLines. Remove the first and last items from the resulting array, turn it back into a string, and then call ReadString. Or you could write the strings to a MemoryStream and call ReadStream.

    0 讨论(0)
  • 2021-02-19 02:50

    the best is to decorate your class with the [IgnoreFirst] attribute.

    If for some reason you can't add the attribute you can do something like this

    var engine = new FileHelperEngine<T>();
    engine.BeforeReadRecord += (e, args) =>
    {
        if (args.LineNumber == 1)
            args.SkipThisRecord = true;
    };
    
    0 讨论(0)
  • 2021-02-19 03:00

    You can use these attributes

    IgnoreFirst: Indicates the numbers of lines to be ignored at the begining of a file or stream when the engine read it.

    [IgnoreFirst(1)] 
    public class OrdersVerticalBar 
    { ...
    

    IgnoreLast: Indicates the numbers of lines to be ignored at the end of a file or stream when the engine read it.

    [IgnoreLast(1)] 
    public class OrdersVerticalBar 
    { ...
    

    You can access the values later with

    engine.HeaderText
    engine.FooterText
    
    0 讨论(0)
提交回复
热议问题