2012-03-30 118 views
0

如何獲取包含文本文件中指定字符串的行號?獲取包含字符串的行號

示例文本文件包含:




綠色

如何獲得 「黃色」 行號?我可以寫一個字符串在指定的行,可以說我想寫一個字符串在第2行?

回答

1

要找到一個文本文件中的行,你需要直到找到來讀取文件的起始行是:

string fileName = "file.txt"; 
string someString = "Yellow"; 

string[] lines = File.ReadAllLines(fileName); 
int found = -1; 
for (int i = 0; i < lines.Length; i++) { 
    if (lines[i].Contains(someString)) { 
    found = i; 
    break; 
    } 
} 

如果你想改變一個線在一個文件中,你必須閱讀整個文件,並將其寫回與改變行:

string[] lines = File.ReadAllLines(fileName); 
lines[1] = "Black"; 
File.WriteAllLines(fileName, lines); 
+0

非常感謝,這工作得很好。 – NetInfo 2012-03-31 01:06:58

1
Dim toSearch = "Yellow" 
Dim lineNumber = File.ReadLines(filePath). 
       Where(Function(l) l.Contains(toSearch)). 
       Select(Function(l, index) index) 

If lineNumber.Any Then 
    Dim firstNumber = lineNumber.First 
End If 

編輯:如果你想要寫在該行的字符串,最好的辦法是更換新的一個行。在下面的例子中,我用「黃色潛水艇」

Dim replaceString = "Yellow Submarine" 
Dim newFileLines = File.ReadLines(filePath). 
        Where(Function(l) l.Contains(toSearch)). 
        Select(Function(l) l.Replace(toSearch, replaceString)) 
File.WriteAllLines(path, newFileLines) 

取代「黃色」的所有出現或者你想更換指定的行:

Dim allLines = File.ReadAllLines(path) 
allLines(lineNumber) = replaceString 
File.WriteAllLines(path, allLines) 
+1

感謝所有這些例子,但我只需要最上面的一個,其無論怎樣我試圖它返回一個錯誤。 – NetInfo 2012-03-31 01:05:37

0
Imports System.IO 

Dim int1 As Integer 
Dim path As String = "file.txt" 
Dim reader As StreamReader 

Public Sub find() 
    int1 = New Integer 
    reader = File.OpenText(path) 
    Dim someString As String = Form1.TextBox1.Text 'this Textbox for searching text example : Yellow 
    Dim lines() As String = File.ReadAllLines(path) 
    Dim found As Integer = -1 
    Dim i As Integer 
    For i = 0 To lines.Length - 1 Step i + 1 
     If lines(i).Contains(someString) Then 
      found = i 
      int1 = i 
      Exit For 
     End If 
    Next 
    reader = File.OpenText(path) 

    'if you want find same word then 

    Dim lines2() As String = File.ReadAllLines(path) 
    Form1.ListBox1.Items.Add(lines2(int1)) 
    int1 = New Integer 
End Sub