Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read fixed width record from text file

Tags:

I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way?

For example, the format could be described as:

<Field1(8)><Field2(16)><Field3(12)>

And an example file with two records could look like:

SomeData0000000000123456SomeMoreData
Data2   0000000000555555MoreData    

I just want to make sure I'm not overlooking a more elegant way than Substring().


Update: I ultimately went with a regex like Killersponge suggested:

private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);
const string REGEX_LOT = "^(?<Field1>.{6})" +
                        "(?<Field2>.{16})" +
                        "(?<Field3>.{12})";

I then use the following to access the fields:

Match match = reLot.Match(record);
string field1 = match.Groups["Field1"].Value;
like image 419
Chris Karcher Avatar asked Oct 02 '08 14:10

Chris Karcher


People also ask

Can a text file be fixed width?

Data in a fixed-width text file is arranged in rows and columns, with one entry per row. Each column has a fixed width, specified in characters, which determines the maximum amount of data it can contain. No delimiters are used to separate the fields in the file.

What is the difference between delimited and fixed width text files?

Fixed format means that the fields in your file have a fixed length. For instance first column is always 10 characters, second is 3 characters and third is 20 characters. Delimited format means that there is a character used to separate every column on each line.


1 Answers

Use FileHelpers.

Example:

[FixedLengthRecord()] 
public class MyData
{ 
  [FieldFixedLength(8)] 
  public string someData; 

  [FieldFixedLength(16)] 
  public int SomeNumber; 

  [FieldFixedLength(12)] 
  [FieldTrim(TrimMode.Right)]
  public string someMoreData;
}

Then, it's as simple as this:

var engine = new FileHelperEngine<MyData>(); 

// To Read Use: 
var res = engine.ReadFile("FileIn.txt"); 

// To Write Use: 
engine.WriteFile("FileOut.txt", res); 
like image 183
Leandro Oliveira Avatar answered Nov 13 '22 20:11

Leandro Oliveira