-1

我有一个文本文件,其中包含这样的数据输入数据文件类型:INdia.Txt

INdia(s) - Input Data File Exists .....

**------------------------------------------**
Feed Counts:
**------------------------------------------**
Records in the Input File            : 04686
Records Inserted in  Table : 04069
Records Inserted in  Table    : 00617
**-------------------------------------------**

我只需要在输出文件中获取这些数据

Records in the Input File  : 04686
Records Inserted in  Table : 04069
Records Inserted in  Table    : 00617 

我正在使用的代码

try
        {
            int NumberOfLines = 15;
            string[] ListLines = new string[NumberOfLines];
            using (FileStream fs = new FileStream(@"d:\Tesco\NGC\UtilityLogs\Store.log", FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);

                        if (line.Contains("Records"))
                        {
                            //Read the number of lines and put them in the array
                            for (int i = 8; i < NumberOfLines; i++)
                            {
                                ListLines[i] = reader.ReadLine();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
4

4 回答 4

2

This LINQ query will give you IEnumerable<string> which will contain all lines from file, which start with "Records" string:

var lines = File.ReadAllLines(path).Where(line => line.StartsWith("Records"));
于 2012-12-13T12:44:32.633 回答
1

尝试这个

   while ((line = reader.ReadLine()) != null)
   {
      if(!line.Contains("Records"))  //if line does not contain "Records"
      {
         continue;  //skip to next line/iteration
      }

      //else
      //process the line  
   }

如果行数已知,那么这可以工作

   int line_number = 1;
   int startline = 15;
   int endline = 100;
   while ((line = reader.ReadLine()) != null)
   {
      if(line_number >= startline && line_number <= endline)  
      {
         //process the line  
      }

      line_number++;
   }
于 2012-12-13T12:28:29.387 回答
0

如果文件中的行数始终相同,请使用:

 string[] lines = File.ReadAllLines(fileName);

 string line1 = lines[5];
 string line2 = lines[6];
 string line3 = lines[6];
 ...

甚至是这样的:

string[] lines = File.ReadAllLines(fileName);
string[] result = new string[3]; // No matter how many, but fixed

Array.Copy(lines, 5, result, result.Length);

如果标题始终为 5 行并且文件始终以一行结尾,您甚至可以拥有动态行数:

string[] lines = File.ReadAllLines(fileName);
string[] result = new string[lines.Length - 6];
Array.Copy(lines, 5, result, result.Length);
于 2012-12-13T12:41:12.410 回答
0

如果您的文件内容固定,请使用 INDEX。

使用 StreamReader 读取文件,然后通过 NEWLINE char 拆分 StreamReader 数据,您将获得一个数组,然后为该数组放置一个索引。

于 2012-12-13T12:29:12.433 回答