2012-10-12 64 views
13

我想在字符串比較的時候在txt文件中找到一個字符串,它應該繼續讀取行,直到我用作參數的另一個字符串。c#在txt文件中搜索字符串

例子:

CustomerEN //search for this string 
... 
some text wich has details about customer 
id "123456" 
username "rootuser" 
... 
CustomerCh //get text till this string 

我需要的細節,否則與他們一起工作。

我使用LINQ搜索「CustomerEN」是這樣的:

File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN")) 

但現在我只能堅持讀線(數據),直到「CustomerCh」提取細節。

+0

聽起來像您需要的正則表達式,而不是LINQ – thumbmunkeys

回答

15

如果你對線的將只在您的文件中出現一次,你可以使用

File.ReadLines(pathToTextFile) 
    .SkipWhile(line => !line.Contains("CustomerEN")) 
    .Skip(1) // optional 
    .TakeWhile(line => !line.Contains("CustomerCh")); 

如果你可以在一個文件中出現多個事件,你最好使用常規的foreach循環 - 讀取行,保持trac你是否目前是內部或外部客戶等K:

List<List<string>> groups = new List<List<string>>(); 
List<string> current = null; 
foreach (var line in File.ReadAllLines(pathToFile)) 
{ 
    if (line.Contains("CustomerEN") && current == null) 
     current = new List<string>(); 
    else if (line.Contains("CustomerCh") && current != null) 
    { 
     groups.Add(current); 
     current = null; 
    } 
    if (current != null) 
     current.Add(line); 
} 
+1

如果您需要區分大小寫的搜索退房http://stackoverflow.com/questions/444798/case-insensitive-containsstring –

2

如果你只有一個第一個字符串,你可以使用簡單的for-loop。

var lines = File.ReadAllLines(pathToTextFile); 

var firstFound = false; 
for(int index = 0; index < lines.Count; index++) 
{ 
    if(!firstFound && lines[index].Contains("CustomerEN")) 
    { 
     firstFound = true; 
    } 
    if(firstFound && lines[index].Contains("CustomerCh")) 
    { 
     //do, what you want, and exit the loop 
     // return lines[index]; 
    } 
} 
4

使用LINQ,你可以使用SkipWhile/TakeWhile方法,像這樣:

var importantLines = 
    File.ReadLines(pathToTextFile) 
    .SkipWhile(line => !line.Contains("CustomerEN")) 
    .TakeWhile(line => !line.Contains("CustomerCh")); 
7

你必須使用while因爲foreach不知道指數。以下是一個示例代碼。

int counter = 0; 
string line; 

Console.Write("Input your search text: "); 
var text = Console.ReadLine(); 

System.IO.StreamReader file = 
    new System.IO.StreamReader("SampleInput1.txt"); 

while ((line = file.ReadLine()) != null) 
{ 
    if (line.Contains(text)) 
    { 
     break; 
    } 

    counter++; 
} 

Console.WriteLine("Line number: {0}", counter); 

file.Close(); 

Console.ReadLine(); 
+0

你並不需要知道索引。 – Rawling

+0

他需要找到第一個字符串,只有在其他關鍵字後纔出現。 –

+0

如果你願意的話,沒有理由不能把這個櫃檯放在foreach中。 – Chris

0

我的工作有點那個Rawling張貼在這裏找到在同一個文件,直到最後多行的方法。這是對我工作:

   foreach (var line in File.ReadLines(pathToFile)) 
       { 
        if (line.Contains("CustomerEN") && current == null) 
        { 
         current = new List<string>(); 
         current.Add(line); 
        } 
        else if (line.Contains("CustomerEN") && current != null) 
        { 
         current.Add(line); 
        } 
       } 
       string s = String.Join(",", current); 
       MessageBox.Show(s);