Reputation: 31
I'm new to C# and writing this application that displays a message if the given name in the TextBox
is in the popular list file. My book gives very little help to fix this, my error is the inputfile of if(boy.Contains(boyinputFile))
same for the girl where it says something about:
cannot convert to string.
private void checkName_Click(object sender, EventArgs e)
{
string boy;
string girl;
girl = girlBox.Text;
boy = boyBox.Text;
StreamReader boyinputFile;
StreamReader girlinputFile;
boyinputFile = File.OpenText("BoyNames.txt");
girlinputFile = File.OpenText("GirlNames.txt");
while (!boyinputFile.EndOfStream)
{
if (boyBox.Text.Contains(boyinputFile))
{
MessageBox.Show("Yes, your name is popular!");
}
}
while (!girlinputFile.EndOfStream)
{
if (girl.Contains(girlinputFile))
{
MessageBox.Show("Yes, your name is popular!");
}
else
{
MessageBox.Show("Sorry, couldn't find your name.");
}
}
boyinputFile.Close();
girlinputFile.Close();
}
Upvotes: 3
Views: 250
Reputation: 19
Replace this line
if (boyBox.Text.Contains(boyinputFile))
with
if (boyBox.Text.Contains(boyinputFile.ToString())).
Upvotes: 0
Reputation: 39966
Try this:
string boy = boyBox.Text;
using (StreamReader sr = new StreamReader("D:\\BoyNames.txt"))
{
string boyinputFile = sr.ReadToEnd();
if (boyinputFil.Contains(boy))
{
MessageBox.Show("Yes, your name is popular!");
}
else
{
MessageBox.Show("Sorry, couldn't find your name.");
}
}
Upvotes: 1
Reputation: 171246
I want to give you better code than the existing answers show you.
var lines = File.ReadAllLines("...");
var isMatch = lines.Contains(name);
It really can be that simple.
Upvotes: 1
Reputation:
You need to convert your stream to a string. This is where you are getting your error:
cannot convert to string
string girl_file = streamReader.ReadToEnd();
You then need to see if the selected name is within the string file. You need to reverse your check. You are checking to see if the textbox contains the file.
if (girl_file.Contains(girl))
{
MessageBox.Show("Yes, your name is popular!");
}
Also have a look at this question How do I convert StreamReader to a string?
Upvotes: 1