如何读取包含多行记录的文件 - C#

Lil*_*ily 0 c# asp.net filestream

我有这个只有一行的文本文件.每个文件包含一个客户名称,但包含多个项目和描述.
以00(公司名称)开头的记录的字符长度为10
01(项目编号) - 字符长度为10
02(描述) - 字符长度为50

我知道如何读取文件,但我不知道如何只循环一行,查找记录00,01,02并根据长度抓取文本,最后从最后记录的位置开始并再次启动循环.有人可以告诉我如何读取这样的文件吗?

输出:

companyName     16622        Description
companyName     15522        Description
Run Code Online (Sandbox Code Playgroud)

输入文本文件示例

00Init    0115522   02Description                                     0116622   02Description                                    
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 7

此解决方案假定数据是固定宽度,并且该项目编号将在描述之前(02之前的01).每次遇到描述记录时,此解决方案都会发出记录,并处理同一公司的多个产品.

首先,定义一个用于保存数据的类:

public class Record
{
    public string CompanyName { get; set; }
    public string ItemNumber { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,遍历您的字符串,在您获得描述时返回记录:

public static IEnumerable<Record> ReadFile(string input)
{
    // Alter these as appropriate
    const int RECORDTYPELENGTH = 2;
    const int COMPANYNAMELENGTH = 41;
    const int ITEMNUMBERLENGTH = 8;
    const int DESCRIPTIONLENGTH = 48;

    int index = 0;
    string companyName = null;
    string itemNumber = null;

    while (index < input.Length)
    {
        string recordType = input.Substring(index, RECORDTYPELENGTH);
        index += RECORDTYPELENGTH;

        if (recordType == "00")
        {
            companyName = input.Substring(index, COMPANYNAMELENGTH).Trim();
            index += COMPANYNAMELENGTH;
        }
        else if (recordType == "01")
        {
            itemNumber = input.Substring(index, ITEMNUMBERLENGTH).Trim();
            index += ITEMNUMBERLENGTH;
        }
        else if (recordType == "02")
        {
            string description = input.Substring(index, DESCRIPTIONLENGTH).Trim();
            index += DESCRIPTIONLENGTH;

            yield return new Record
            {
                CompanyName = companyName,
                ItemNumber = itemNumber,
                Description = description
            };
        }
        else 
        {
            throw new FormatException("Unexpected record type " + recordType);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,问题中的字段长度与示例数据不匹配,因此我对其进行了调整,以使解决方案能够处理您提供的数据.您可以通过调整常量来调整字段长度.

使用如下:

string input = "00CompanyName                              0115522   02Description                                     0116622   02Description                                     ";

foreach (var record in ReadFile(input))
{
    Console.WriteLine("{0}\t{1}\t{2}", record.CompanyName, record.ItemNumber, record.Description);
}
Run Code Online (Sandbox Code Playgroud)