我正在try 编写C#代码来搜索文本文件中的特定字符串,并显示它是在哪一行找到的,或者如果找不到该字符串,则显示一条消息.我try 了几段不同的代码,但它们只有在找到字符串时才会执行某些操作.如果我放了一条Else语句来显示文本Not Found消息,如果找不到字符串,它就会忽略它.使用"While"循环结束时不执行任何操作,或者即使找到了字符串,它也会显示"未找到字符串"消息.我try 了循环和Foreach循环,但仍然没有得到我想要的结果.文本文件每行有一个单词.
以下是我拥有的代码:
public long CountLinesReader(string file)
{
var lineCounter = 0L;
using (StreamReader reader = new(file))
{
while (reader.ReadLine() != null)
{
lineCounter++;
}
return lineCounter;
}
}
private void BtnSearch_Click(object sender, EventArgs e)
{
StrSearchTerm = TxtSearchTerm.Text;
StrTextFile = @Application.StartupPath + @"\TextFile.txt";
IntLineCount = (int)CountLinesReader(StrTextFile);
for(int i = 0; i < IntLineCount; i++)
{
System.IO.StreamReader file = new System.IO.StreamReader(StrTextFile);
while ((line = file.ReadLine()) != null)
{
StrLine = line;
if(StrLine == StrSearchTerm)
{
LblSearch.Text = StrSearchTerm + " found on line: "+ i.ToString();
}
}
if (StrLine == string.Empty)
{
LblSearch.Text = "The word: " + StrSearchTerm + " not found.";
}
}
}