2012-03-30 123 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 
相关问题