One of the possible ways, perhaps not the best, but, as an example, use layout structures for this:
... using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct Type1 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public char[] FirstName; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public char[] LasteName; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)] public char[] Address; ... }
And the use will be as follows:
using (TextReader reader = File.OpenText(@"D:\flatfile.txt")) { string line = reader.ReadLine(); string code = line.Substring(0, 5);
You can find a good description of using layout structure here .
Btw, you can use strings instead of a char array as a property type with the following attribute:
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)] public string FirstName;
but in this case the last character of the line will be lost - it is replaced with '/ 0' (considered as a line with zero termination).
source share