平面文件解析器例程

我们有一个平面文件。每行的前五个字符决定了该行所属的类型。 每种类型都有很少的字段,都是固定长度。 我如何解析文件并将其存储在数据库中?

几种选择:

1)为每种类型创建一个XML模板,并根据前五个字符确定用于解析该行的模板

        

2)使用fileHelpers库( http://www.filehelpers.net/ )

还有其他建议吗? 请告诉我

Microsoft.VisualBasic.FileIO.TextFieldParser类可以很好地解析结构化文本文件。 您可以从C#中使用它。 只需添加对Microsoft.VisualBasic.dll的引用,并在代码中using Microsoft.VisualBasic.FileIO语句。

简单的字符串IndexOf,Substring是不够的?

可能的方法之一,可能不是最好的,但仅作为一个例子 – 是使用layouted结构:

 ... 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; ... } 

用法如下:

 using (TextReader reader = File.OpenText(@"D:\flatfile.txt")) { string line = reader.ReadLine(); string code = line.Substring(0, 5); // Add your structures factory realization Type type = Factory.GetStructureByCode(code); string typeInitializtion = line.Substring(5, (line.Length - 5)); byte[] bytes = Encoding.UTF8.GetBytes(typeInitializtion); //Allocate amount of memoty IntPtr safePrt = Marshal.AllocCoTaskMem(Marshal.SizeOf(type)); //Copy 'bytes' byte buffer into memmory allocated Marshal.Copy(bytes, 0, safePrt, bytes.Length); //Map structure to pointer var myStructure = Marshal.PtrToStructure(safePrt, type); } 

你可以在这里找到关于结构布局用法的很好的描述

顺便说一句,您可以使用字符串而不是char数组作为属性类型,具有以下属性:

  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)] public string FirstName; 

但在这种情况下,字符串的最后一个字符将丢失 – 它被替换为’/ 0’(被视为以空字符结尾的字符串)。

如果您想自己滚动:使用Insert命令,捕获RegExp以及从RegExp组到命令参数的映射关联每个类型。