![](/img/trans.png)
[英]C#: Using StreamReader to read line from txt file, but Peek() return -1 even there are a lot of lines left
[英]Read all lines from TXT file and search only in every FIRST string of each line C#
我在listView中显示搜索结果时遇到问题。 我有一个TXT文件,我只想搜索文件每一行的开头单词。 我不知道应该采取什么条件来执行此操作...我正在阅读有关FirstORDefault选项的信息,但不适用于我的if语句。 以下是我的文本文件和显示视图表单。
我希望能收到您的来信。 请帮忙。
private void btnSH_Click(object sender, EventArgs e)
{
FileStream history = File.Open("C:\\Users\\Sofia\\TestFolder2\\logfile.txt", FileMode.Open, FileAccess.Read);
StreamReader hRead = new StreamReader(history);
String viewHistory = hRead.ReadToEnd();
String[] hArray = viewHistory.Split('\n');
hRead.Close();
history.Close();
if (txtBoxSH2.Text != "")
{
string searchString = txtBoxSH2.Text;
historyLstBox.Items.Clear();
foreach (string line in hArray)
{
if (line.ToUpper().IndexOf(searchString.ToUpper())!= -1)
{
historyLstBox.Items.Add(line);
}
}
}
}
您可以使用LINQ提供更简洁的代码:
private IEnumerable<string> GetMatchingLines(string filename, string word)
{
return File.ReadLines(filename)
.Where(line => string.Equals(line.Split(' ').FirstOrDefault(),
word,
StringComparison.InvariantCultureIgnoreCase));
}
然后只需将此方法的结果添加到historyLstBox.Items
。
您可以使用line.StartsWith(searchString)代替line.IndexOf(searchString)
http://msdn.microsoft.com/zh-CN/library/baketfxw(v=vs.110).aspx
我将为此使用File.ReadLines
。
string searchString = txtBoxSH2.Text;
if (searchString == "")
return;
foreach (string line in File.ReadLines("C:\\Users\\Sofia\\TestFolder2\\logfile.txt"))
{
if (String.IsNullOrWhitespace(line))
continue;
if (line.Split(' ')[0].ToUpper() == searchString)
historyLstBox.Items.Add(line);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.