Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 exception due to this. All other lines have proper fixed width. How to skipt first and last lines or other way to read data without exception ?

    [FixedLengthRecord()]
    class Bank
    {
        [FieldFixedLength(4)]
        public string AINETUNNUS;
        [FieldFixedLength(16)]
        public string TEKST1;
        [FieldFixedLength(3)]
        public string opliik;
        [FieldFixedLength(2)]
        public string hinnalis;
    };

    [AcceptVerbs(HttpVerbs.Post)]
    [Authorize]
    public ActionResult LoadStatement(HttpPostedFileBase uploadFile)
    {

        FileHelperEngine engine = new FileHelperEngine(typeof(Bank));
        var res = engine.ReadStream(new StreamReader(uploadFile.InputStream,
             Encoding.GetEncoding(1257))) as Bank[];
  }
like image 690
Andrus Avatar asked Jun 12 '12 16:06

Andrus


2 Answers

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
like image 110
Marcos Meli Avatar answered Oct 16 '22 02:10

Marcos Meli


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.

like image 33
Jim Mischel Avatar answered Oct 16 '22 01:10

Jim Mischel