Click here to Skip to main content
Click here to Skip to main content

A Portable and Efficient Generic Parser for Flat Files

By , 16 Jul 2012
 

Introduction

We, as developers, are often faced with converting data from one format to another. For a project at work, I needed a portable solution that was efficient, had minimal external requirements, and parsed delimited and fixed-width data. As shown below, the GenericParser is a good replacement for any Microsoft provided solution and provides some unique functionality. The code is well organized and easy to follow to allow modification as necessary.

Note: The project was built using Visual Studio 2010, but the code is designed for .NET 2.0.

Definitions

  • Delimited data - Data whose columns are separated by a specific character (e.g., CSV - Comma Separated Values).
  • Fixed-width data - Data whose columns are of a set number of characters wide.

Features

The GenericParser (and the derived GenericParserAdapter) contains the following features:

  • Efficient - See Benchmarking below for more details.
    • Time: Approximately 3 to 10 times faster than any Microsoft provided solution
    • Memory: Approximately equal to or less than any Microsoft provided solution
  • Supports delimited and fixed-width formats
  • Supports a custom delimiter character (single character only)
  • Supports comment rows (single character marker)
  • Supports escape characters (single character only)
  • Supports a custom text qualifier to allow column/row delimiters to be ignored (e.g., multi-line data)
  • Supports escaped text qualifiers by doubling them up
  • Supports ignoring/including rows that contain no characters
  • Supports a header row
  • Supports the ability to dynamically add more columns to match the data
  • Supports the ability to enforce the number of columns to a specific number
  • Supports the ability to enforce the number of columns based on the first row
  • Supports trimming the strings of a column
  • Supports stripping off control characters
  • Supports reusing the same instance of the parser for different data sources
  • Supports TextReader and String (the file location) as data sources
  • Supports limiting the maximum number of rows to read
  • Supports customizing the size of the internal buffer
  • Supports skipping rows at the beginning of the data after the header row
  • Supports XML configuration which can be loaded/saved in numerous formats
  • Supports access to data via column name (when a header row is supplied)
  • Supports Unicode encoding
  • GenericParserAdapter supports skipping rows at the end of the data
  • GenericParserAdapter supports adding a line number to each row of output
  • GenericParserAdapter supports the following outputs - XML, DataTable, and DataSet
  • Thorough unit testing - 91.94% code coverage (tests supplied in source download)
  • Thorough XML documentation in code (including a .chm help file in the binary/source downloads)

Benchmarking

To benchmark the GenericParser, I chose to compare it to:

  • Microsoft's Text Driver
  • Microsoft's Text Field Parser
  • Sebastien Lorion's CsvReader 3.7 (CSV only - code found here[^])
  • GenericParser 1.0

To get a realistic datasource for benchmarking, I took 10 rows of data from the Northwind Database and replicated them for successively larger and larger sets of CSV and FixedWidth data. Using System.Diagnostics.Stopwatch to measure CPU usage, I executed each benchmark 10 times and averaged the results to minimize the amount of error in the instrumentation. For the memory usage, I used Visual Studio 2010's memory profiling and executed each benchmark only once.

I've tried to generate tests that exercise the code equally for each solution. As a caveat, these tests do not test every possible scenario - your mileage may vary. Please feel free to use my code as a basis (or create your own tests) to compare the code before you draw any conclusions.

For example, the tests below did not take into account escaped characters. In GenericParser 1.0, it allocated an additional buffer for escaped characters, which essentially doubled its memory requirements. In GenericParser 1.1, it reuses the existing buffer to unescape the column of data. You wouldn't see this benefit unless you specifically geared your tests to account for this.

Just because I know someone will comment about this, I am aware of FileHelpers[^], but I believe they fit into a different category which doesn't map easily for comparison to the above solutions. FileHelpers rely on a declarative definition of the file schema through attributes on concrete classes.  My solution depends on defining the schema through properties or XML.   You may feel free to compare them, if they fit into your problem space.

CPU Usage

Memory Usage

Note: Because profiling the memory was generating .vsp files upwards of 2 gigs and the memory usage seemed pretty stable, I only executed memory profiling for 10 to 10,000 rows of data.

Conclusion

As can be seen in the charts, GenericParser meets or exceeds anything Microsoft has put together in all areas. Furthermore, version 1.1 out performs version 1.0 in performance considerably, especially considering the bug fixes and the new features added.

As can be seen by the graphs, Sebastien Lorion's CsvReader is definitely the top contender for parsing delimited files. So, if you are looking at only parsing delimited files, I would highly recommend checking out his library. Otherwise, I find my library to be an effective implementation for being able to parse both formats.

In the source download, you can find all of my performance tests and results, including an Excel 2010 workbook that has all of the collected raw data together for charting purposes.

Using the Code

The code itself mimics most readers found within the .NET Framework, but the usage follows four basic steps:

  1. Set the data source through either the constructor or the SetDataSource() method.
  2. Configure the parser for the data source's format, either through properties, or by loading an XML CONFIG file via the Load() method.
  3. Call the Read() method and access the columns of data underneath, or for the GenericParserAdapter - GetXml(), GetDataTable(), GetDataSet() to extract data.
  4. Call Close() or Dispose().
DataSet dsResult;
 
// Using an XML Config file. 
using (GenericParserAdapter parser = new GenericParserAdapter("MyData.txt"))
{
    parser.Load("MyData.xml");
    dsResult = parser.GetDataSet();
}
 
// Or... programmatically setting up the parser for TSV. 
string strID, strName, strStatus;
using (GenericParser parser = new GenericParser())
{
    parser.SetDataSource("MyData.txt");
 
    parser.ColumnDelimiter = "\t".ToCharArray();
    parser.FirstRowHasHeader = true;
    parser.SkipStartingDataRows = 10;
    parser.MaxBufferSize = 4096;
    parser.MaxRows = 500;
    parser.TextQualifier = '\"';
 
    while (parser.Read())
    {
      strID = parser["ID"];
      strName = parser["Name"];
      strStatus = parser["Status"];
 
      // Your code here ...
    }
}
 
// Or... programmatically setting up the parser for Fixed-width. 
  using (GenericParser parser = new GenericParser())
  {
    parser.SetDataSource("MyData.txt");
 
    parser.ColumnWidths = new int[4] {10, 10, 10, 10};
    parser.SkipStartingDataRows = 10;
    parser.MaxRows = 500;
 
    while (parser.Read())
    {
      strID = parser["ID"];
      strName = parser["Name"];
      strStatus = parser["Status"];
 
      // Your code here ...
    }
}

Acknowledgements

While I did not create a derivative of Sebastien Lorion's CsvReader, I did use some of his concepts of provided functionality in his CsvReader for the GenericParser.

Tools Used

History

  • September 17, 2005 - 1.0 - First release
  • June 20, 2010 - 1.1
    • New features:
      • Supports ignoring/including blank rows of data (no characters found in row)
      • Supports the ability to enforce the number of columns based on the first row
      • Supports stripping off control characters
      • GenericParserAdapter supports skipping rows at the end of the data
      • Reduced memory overhead when using escaped characters
      • Support for specifying the data's encoding
    • Bug fixes:
      • Fixed a bug with parsing data with a header and no data
      • Fixed a bug in not handling text qualifiers/escape/comment characters consistently
      • Fixed a bug in reading a file across a high latency network
      • Fixed a bug with text qualifiers being interpreted in the middle of the column (only works if at the start and end of a column)
      • Fixed a bug with skipping row ends at the very end of the buffer
    • Breaking changes:
      • Fixed width parsing will no longer take text qualifiers or escape characters into account
      • The following properties have been converted to a char?:
        • ColumnDelimiter
        • CommentCharacter
        • EscapeCharacter
        • TextQualifier
      • RowDelimiter has been removed, and the code automatically handles looking for '\n' or '\r' to indicate a new row (assuming '\r' is not a column delimiter). If one of these characters is found, it will skip the paired '\n' or '\r' (assuming '\r' is not a column delimiter).
      • SkipDataRows has been renamed to SkipStartingDataRows
      • The FixedWidth property has been replaced by a property called TextFieldType, which is of the enum type FieldType
      • Due to the changes in the properties listed above, the XML produced by version 1.0 will not be 100% compatible with version 1.1
      • Read() will return true if it parses a header row and no data
      • ParserSetupException has been replaced by InvalidOperationException
      • Reworked the messages supplied in the exceptions to be more descriptive.
  • June 26, 2010 - 1.1.1
    • New features:
      • Reworked benchmarking to be more representative of real world data and switched over testing to not use DataSets
      • Slightly more efficient loading of configuration files
  • February 5, 2012 - 1.1.2
    • Bug fixes:
      • Fixed an issue where an exception was being thrown for the MaxBufferSize was too small, when it was indeed large enough (Reported by uberblue).
  • March 16, 2012 - 1.1.3
    • Bug fixes:
      • Fixed an issue where control characters were being removed accidently (Reported by John Voelk).
      • Fixed an issue where data at the end of the stream wasn't extracted properly (introduced in version 1.1.2).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andrew Rissing
Software Developer (Senior)
United States United States
Member
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.
 
So..If you're not moving forward, you're moving backwards.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Request support for variable length fixed length flat filesmemberAndrew Rissing23 Jul '12 - 9:19 
GeneralRe: Request support for variable length fixed length flat filesmemberMember 777899523 Jul '12 - 9:36 
GeneralRe: Request support for variable length fixed length flat filesmemberMember 96487935 Dec '12 - 20:04 
GeneralMy vote of 5memberSteve Pinckney16 Jul '12 - 10:00 
GeneralRe: My vote of 5memberAndrew Rissing16 Jul '12 - 12:33 
QuestionFileHelpersmemberSteve Pinckney16 Jul '12 - 9:58 
AnswerRe: FileHelpersmemberAndrew Rissing16 Jul '12 - 12:32 
GeneralRe: FileHelpersmemberAndrew Rissing16 Jul '12 - 13:57 
GeneralRe: FileHelpersmemberSteve Pinckney17 Jul '12 - 5:58 
GeneralRe: FileHelpersmemberAndrew Rissing17 Jul '12 - 8:12 
Questionminor editorial suggestionmemberBillWoodruff14 Jul '12 - 5:58 
GeneralRe: minor editorial suggestionmemberAndrew Rissing14 Jul '12 - 16:22 
GeneralEncoding.Unicode and parser.MaxBufferSize = 65536; -> MaxBufferSize exceeded. Try increasing the buffer sizememberMember 356666713 Jul '12 - 6:14 
I have trouble for French Names (Sébastien) encoding.
With no encoding:
using (GenericParsing.GenericParserAdapter parser = new GenericParsing.GenericParserAdapter(CsvFile_FullPathSrv))
the parsing result is : S�bastien.
I don’t know the content (number of columns end encoding type) of customer csv file before parsing.
To be sure all data will be correct encoded I’m using Unicode encoding and buffer size increasing up to 65536.
 
using (GenericParsing.GenericParserAdapter parser = new GenericParsing.GenericParserAdapter(CsvFile_FullPathSrv, System.Text.Encoding.Unicode))
parser.MaxBufferSize = 65536;
As result I receiving thrown exception in GenericParser.cs line 2315: 
            // Make sure we haven't exceeded our buffer size.
            if ((intStartIndex == 0) && (this.m_intNumberOfCharactersInBuffer == this.m_intMaxBufferSize))
this.m_intNumberOfCharactersInBuffer	0x00010000	int
this.m_intMaxBufferSize			0x00010000	int
Same problem if I'm using StreamReader:
using (GenericParsing.GenericParserAdapter parser = new GenericParsing.GenericParserAdapter(new System.IO.StreamReader(CsvFile_FullPathSrv)))
                {
                    parser.FirstRowHasHeader = true;
                    using (DataTable dtResult = parser.GetDataTable())
                    {
                        return dtResult;
                    }
                }
Thank you for really amazing parsing tool. Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
GeneralRe: Encoding.Unicode and parser.MaxBufferSize = 65536; -> MaxBufferSize exceeded. Try increasing the buffer sizememberAndrew Rissing13 Jul '12 - 8:29 
GeneralRe: Encoding.Unicode and parser.MaxBufferSize = 65536; -> MaxBufferSize exceeded. Try increasing the buffer sizememberMember 356666716 Jul '12 - 4:15 
GeneralRe: Encoding.Unicode and parser.MaxBufferSize = 65536; -> MaxBufferSize exceeded. Try increasing the buffer sizememberschuster19uk16 Jul '12 - 11:34 
QuestionSkipDataRows not found in Generic Parsermemberschuster19uk13 Jul '12 - 1:16 
AnswerRe: SkipDataRows not found in Generic ParsermemberAndrew Rissing13 Jul '12 - 8:09 
GeneralRe: SkipDataRows not found in Generic Parsermemberschuster19uk16 Jul '12 - 11:29 
GeneralRe: SkipDataRows not found in Generic ParsermemberAndrew Rissing16 Jul '12 - 12:26 
QuestionIssue using delimiters in extended ASSCI.memberrye046 Jul '12 - 18:45 
AnswerRe: Issue using delimiters in extended ASSCI.memberAndrew Rissing7 Jul '12 - 6:11 
QuestionNuget packagememberrowillis20 May '12 - 16:25 
QuestionLoading very large data filesmemberexwhyz16 May '12 - 18:13 
AnswerRe: Loading very large data filesmemberAndrew Rissing17 May '12 - 3:28 
GeneralRe: Loading very large data filesmemberexwhyz17 May '12 - 8:51 
GeneralRe: Loading very large data filesmemberAndrew Rissing18 May '12 - 5:17 
QuestionUTF-16membergwired25 Apr '12 - 8:25 
AnswerRe: UTF-16memberAndrew Rissing26 Apr '12 - 3:25 
GeneralRe: UTF-16membergwired29 Apr '12 - 14:28 
QuestionFixedWidth filed with no LFmemberMember 854119729 Mar '12 - 8:54 
AnswerRe: FixedWidth filed with no LFmemberAndrew Rissing30 Mar '12 - 3:56 
SuggestionSkip header rowsmemberMember 770605219 Mar '12 - 10:55 
GeneralRe: Skip header rowsmemberAndrew Rissing19 Mar '12 - 14:48 
QuestionEmbedded tab character being removedmemberJohn Voelk15 Mar '12 - 17:24 
AnswerRe: Embedded tab character being removedmemberAndrew Rissing16 Mar '12 - 5:07 
GeneralRe: Embedded tab character being removedmemberAndrew Rissing16 Mar '12 - 8:12 
GeneralRe: Embedded tab character being removedmemberJohn Voelk16 Mar '12 - 12:09 
GeneralGreat!memberkaan0523 Jan '12 - 4:22 
BugObscure "Increase max buffer size" exception when buffer isn't full (and is large!)memberuberblue17 Jan '12 - 7:53 
GeneralRe: Obscure "Increase max buffer size" exception when buffer isn't full (and is large!)memberAndrew Rissing5 Feb '12 - 8:12 
QuestionConsecutive white spacememberMember 844045528 Nov '11 - 5:17 
AnswerRe: Consecutive white spacememberMember 844045528 Nov '11 - 6:24 
GeneralRe: Consecutive white spacememberAndrew Rissing28 Nov '11 - 12:18 
GeneralRe: Consecutive white spacememberMember 844045528 Nov '11 - 21:40 
QuestionDisappearing charactermemberMember 740216624 Aug '11 - 0:33 
AnswerRe: Disappearing charactermemberAndrew Rissing24 Aug '11 - 4:01 
QuestionNull Text QualifiermemberGopi Sundharam28 Jun '11 - 1:45 
AnswerRe: Null Text QualifiermemberAndrew Rissing28 Jun '11 - 5:03 
GeneralRe: Null Text QualifiermemberGopi Sundharam28 Jun '11 - 6:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 17 Jul 2012
Article Copyright 2005 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid