-1

I have a fixed position ascii file that I need to parse. The file gets passed in as a text document with hundreds or thousands of rows. Each row is about 100 characters wide. Each data element is varying length. I really do not want to manually parse each data element. I remember way, way back in the day when I coded in "C", that we could take some data, and overlay a struct, and then reference the data elements in the struct. I have done some research, and I don't see any solid examples on how to do this in C#. Any suggestions on how to parse this data?

This is an example of what the data could look like:

Mr John Doe 123 Main St. New York NY11111
MrsMelissa Schwartzen4444 Mississippi St.Philadelphia PA11111

Title - Starts at column 0, has a lenth of 3. FirstName - Starts at column 3, has a length of 10. LastName - Starts at column 13, has a length of 10. Address - Starts at column 23, has a length of 20. City - Starts at column 43, has a length of 15. State - Starts at column 58, has a length of 2. Zip - Starts at column 60, has a length of 5.

The first thought to parse this data might be to iterate through each line in the file and get substrings for the Title, FirstName, LastName, Address, etc. But there has to be a more elegant way to parse this data. That is why I am asking if there is a way to use a pointer and overlay the data with a struct. This is an unmanaged solution, but I can't think of any better ways to approach this. Unless one of you smart and clever people can suggest something.

BriceTRockindale
  • 309
  • 1
  • 4
  • 15
  • 2
    Where's the code? What have you tried so far? What file structure are you talking about? What is a "data element"? – Tarec Feb 01 '14 at 01:19
  • Is http://stackoverflow.com/questions/162727/read-fixed-width-record-from-text-file what you are looking for? – akton Feb 01 '14 at 01:21
  • I added some more detail. Thanks for the comments so far, but I am trying to solve this issue in a more elegant manner than to create substrings. – BriceTRockindale Feb 01 '14 at 03:31

1 Answers1

0

Microsoft was nice enough to provide us with the TextFieldParser class.

And here's an example of how to use it.

Code from the example page

Using Reader As New Microsoft.VisualBasic.FileIO.
   TextFieldParser("C:\TestFolder\test.log")

   Reader.TextFieldType =
      Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
   Reader.SetFieldWidths(5, 10, 11, -1)
   Dim currentRow As String()
   While Not Reader.EndOfData
      Try
         currentRow = Reader.ReadFields()
         Dim currentField As String 
         For Each currentField In currentRow
            MsgBox(currentField)
         Next 
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
         MsgBox("Line " & ex.Message &
         "is not valid and will be skipped.")
      End Try 
   End While 
End Using
Sam Axe
  • 33,313
  • 9
  • 55
  • 89