lucycopp lucycopp - 4 months ago 16
C# Question

Search Method through text file c#

I have made an application which saves and loads data from a text file. What I want to do is search for a string, display that string as well as the two strings after in the appropriate places of the WPF.
I think it is finding the string okay because the counter is displaying correctly however none of the strings are displaying. Here is my search method:

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;


}


any ideas?

Answer

I think you flipped the assignment:

productNameBlock.Text = allLines[counter];
customerNameBlock.Text = allLines[counter + 1];
firmwareBlock.Text = allLines[counter + 2];

Second, you're not using lineCount so just remove that extra reading line.