1

I got a flat file where the data is not delimetered or something else. The file contains one large string and one row is represented by 180 chars.

Each column value is definied by a length of chars. I have to create an object for each row, parse the 180 chars and fill properties of the created object with the parsed values.

How can i solve this problem without permanent using substring or something else?

Maybe some nice solution with Linq?

Thanks a lot.

4 Answers 4

1

Solution 1 - Super fast but unsafe:

  • Create your class with [StructLayout(LayoutKind.Sequential)] and all other unmanaged code markings for length. Your strings will be char array but can be exposed as string after loading.
  • Read 180 bytes and create a byte array of the same size inside a fixed block
  • Change pointer to IntPtr and use Marshal.PtrToStructure() to load an onject of your class

Solution 2 - Loading logic in the class:

  • Create a constructor in your class that accepts byte[] and inside the objects using Covenrt.Toxxx or Encoding.ASCII.ToString() assuming it is ASCII
  • Read 180 bytes and create an object and pass it to .ctor
  • If you have to serialise back to byte[] then implement a ToByteArray() method and again use Covenrt.Toxxx or Encoding.ASCII.ToString() to write to byte.

Enhancement to solutions 2:

Create custom attributes and decorate your classes with those so that you can have a factory that reads metadata and inflates your objects using byte array for you. This is most useful if you have more than a couple of such classes.

Alternative to solutions 2:

You may pass stream instead of a byte array which is faster. Here you would use BinaryReader and BinaryWriter to read and write values. Strings however is a bit trick since it writes the length as well I think.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a StringReader to parse your text, then you won't have to use substring. Linq won't help you here.

Comments

0

I agree with OJ but even with StringReader you will still need the position of each individual value to parse it out of the string...there is nothing wrong with substring just make sure you use static constants when defining the begging and ending lengths. Example:

private static int VAR_START_INDEX = 0;
private static int VAR_END_INDEX = 4;

String data = "thisisthedata";

String var = data.Substring(VAR_START_INDEX,VAR_END_INDEX);
//var would then be equal to 'this'

1 Comment

VAR_END_INDEX should really be called VAR_LENGTH
0

This library can help you http://f2enum.codeplex.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.