拆分具有不同大小的固定宽度的文本文件



我遇到了一个问题,我需要拆分一个固定宽度的文件。每个字段都可以通过其第一个字符来标识。

该文件包含多种格式,例如,第一行的格式是{1,11,12},而第二行的格式是{1,10,12}。两者都用第一个字符标识。

AFirstField SecondFields
BBField    SecondFields

但是,有时一行可能带有较少的字符,如下所示。

AFirstField S

到目前为止,我尝试的是使用文本解析器获取当前行并检查第一个字符以确定格式,但是应用程序会失败,因为有时行上的数据较少,如上面的 A 示例。

string[] data;
using (TextFieldParser myReader = new TextFieldParser(filePath))
{
myReader.TextFieldType = FieldType.FixedWidth;
while (!myReader.EndOfData)
{
currentLine = myReader.ReadLine();
recordType = currentLine[0].ToString();
if (!recordType.Equals("H"))
{
myReader.FieldWidths = returnLineFormat();
myReader.HasFieldsEnclosedInQuotes = true;
data = myReader.ReadFields();

//if (recordType.Equals("R"))
//{
//    ISD.Add(data);
//}
}
}
}

private int[] returnLineFormat()
{
int[] format = null;
if ((recordType == "A"))
{
format = new int[] { 1, 11, 12};
}
else if ((recordType == "B"))
{
format = new int[] { 1, 10, 12};
}
return format;
}

这些是我遇到的错误,导致行的内容较少: 第 3 行不能使用当前的字段宽度进行分析。

有没有办法解决这个问题?

试试这个。它应该工作

static int[] returnLineFormat(string recordType)
{
int[] format = null;
if ((recordType == "A"))
{
format = new int[] { 1, 11, 12 };
}
else if ((recordType == "B"))
{
format = new int[] { 1, 10, 12 };
}
return format;
}
static void Main(string[] args)
{
string[] data;
using (TextFieldParser myReader = new TextFieldParser(@"TextParserExample.txt"))
{
myReader.TextFieldType = FieldType.FixedWidth;
while (!myReader.EndOfData)
{
var recordType = myReader.PeekChars(1);
if (!recordType.Equals("H"))
{
var lineLength = myReader.PeekChars(1000).Length;
var currentLine = myReader.ReadLine();
var lengths = returnLineFormat(recordType);
lengths[2] = lineLength - (lengths[0] + lengths[1]);
myReader.FieldWidths = lengths;
myReader.HasFieldsEnclosedInQuotes = true;
data = myReader.ReadFields();
}
}
}
}

最新更新