2012-12-13 24 views
-1

我有這樣的 輸入數據文件類型數據的文本文件得到specfic行:INdia.Txt如何在C#中的文本文件

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

有這方面的幫助將是巨大

感謝 王子

回答

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

如果你的文件是固定的內容,然後使用索引。

用StreamReader讀取文件,然後通過NEWLINE字符串分割StreamReader數據,您將得到一個數組,然後爲該數組設置一個索引。

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

此LINQ查詢會給你IEnumerable<string>其中包含文件中以「Records」字符串開頭的所有行:

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

Ha!這很棒!從我+1。 –

相關問題