簡體   English   中英

如何從C#中的文本文件獲取特定行

[英]How to get specfic lines from a text file in C#

我有一個文本文件,其數據是這樣的輸入數據文件類型: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;
        }

此LINQ查詢將為您提供IEnumerable<string> ,它將包含文件中所有以“ Records”字符串開頭的行:

var lines = File.ReadAllLines(path).Where(line => line.StartsWith("Records"));

嘗試這個

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

如果文件內容固定,則使用INDEX。

使用StreamReader讀取文件,然后通過NEWLINE char拆分StreamReader數據,您將獲得一個數組,然后為該數組放置一個索引。

如果文件中的行數始終相同,請使用:

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM