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. 正则表达式获取包含引号的字符串
- 2. 字符串包含引号字符( ')
- 3. 获取从包含特定字符串
- 4. 如何从包含“,”的字符串获取字符串值?
- 5. 从包含多行的字符串获取最后一行
- 6. 如何获取包含字符串的整行文本
- 7. 如何从字符串中获取数组包含Ruby中相同的符号?
- 8. 加入号码包含在字符串
- 9. Perl字符串包含括号
- 10. 在字符串中包含引号?
- 11. 如何获取包含来自C中字符串的字的子字符串?
- 12. 包含完整字符串分隔符的提取字符串
- 13. 从textarea获取带有字符串(“行号”)的行号?
- 14. 包含逗号与逗号分隔符的分割字符串
- 15. 包含引号的YAML中的多行字符串
- 16. 从Java中的字符串中获取int也包含字母
- 17. 从多个类获取包含字符串和数字的类
- 18. 字符串包含
- 19. 包含字符串
- 20. 如何在子字符串包含等号时执行子字符串替换?
- 21. 如何从搜索字符串中返回包含撇号的查询结果字符串不包含撇号
- 22. 如何获取包含在指定字符串中的特定字符串?
- 23. 从包含特殊字符的字符串中提取子串
- 24. 如何获取包含字段中的字符串的所有行(SQL)?
- 25. Awk获取包含逗号和换行符的.csv列
- 26. 连接一个包含反引号字符的字符串R
- 27. PHP字符串包含HTML号的特殊字符代码
- 28. 分割包含逗号(特殊字符?)的字符串
- 29. 提取所有行,包括包含子字符串和Python中的子字符串后面的行的行
- 30. 当字符串包含“&”符号时值超过分号
非常感谢,这工作得很好。 – NetInfo 2012-03-31 01:06:58