【发布时间】:2016-08-05 13:17:26
【问题描述】:
我制作了一个应用程序,它可以从文本文件中保存和加载数据。我想要做的是搜索一个字符串,在 WPF 的适当位置显示该字符串以及后面的两个字符串。 我认为它可以找到字符串,因为计数器显示正确,但是没有显示任何字符串。这是我的搜索方法:
public void Search(string searchTerm)
{
var lineCount = File.ReadLines("products.txt").Count();
string line;
int counter = 0;
System.IO.StreamReader file = new System.IO.StreamReader("products.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(searchTerm))
{
break;
}
counter++;
}
textBlock.Text = counter.ToString();
string[] allLines = File.ReadAllLines("products.txt");
allLines[counter] = productNameBlock.Text;
allLines[counter + 1] = customerNameBlock.Text;
allLines[counter + 2] = firmwareBlock.Text;
}
有什么想法吗?
【问题讨论】:
-
听起来 products.txt 应该是结构化格式,如 XML(或 SQLite),其设计目的是使查找/更改/保存数据变得容易,而无需遍历整个文本文件。
-
您正在阅读文件中的所有行至少 3 次 - 为什么?这是非常低效的。您应该只执行一次。
-
啊,真烦人!