0
A
回答
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);
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
相關問題
- 1. 字符串中包含5號和行
- 2. 正則表達式獲取包含引號的字符串
- 3. 字符串包含引號字符( ')
- 4. 獲取從包含特定字符串
- 5. 獲取字符串中包含的所有字符串
- 6. 如何從包含「,」的字符串獲取字符串值?
- 7. 從包含多行的字符串獲取最後一行
- 8. 獲取字符串是即使它包含一個換行符
- 9. 如何獲取包含字符串的整行文本
- 10. 使字符串文字自動包含換行符號?
- 11. 如何從字符串中獲取數組包含Ruby中相同的符號?
- 12. jQuery獲取輸入字段的值,其中字符串包含括號?
- 13. 在字符串中包含引號?
- 14. 檢查字符串包含2號
- 15. 在字符串中包含單引號
- 16. 加入號碼包含在字符串
- 17. Perl字符串包含括號
- 18. 如何獲取包含來自C中字符串的字的子字符串?
- 19. 包含完整字符串分隔符的提取字符串
- 20. Ruby從包含子串的數組中獲取字符串
- 21. 從包含特定字符串的文本字段獲取字符串
- 22. 從textarea獲取帶有字符串(「行號」)的行號?
- 23. 包含逗號與逗號分隔符的分割字符串
- 24. 抓取包含特定子字符串的特定修訂號
- 25. 獲取符號之間的字符串
- 26. 包含引號的YAML中的多行字符串
- 27. 字符串包含
- 28. 字符串包含
- 29. 包含字符串
- 30. 從多個類獲取包含字符串和數字的類
非常感謝,這工作得很好。 – NetInfo 2012-03-31 01:06:58