Reputation: 57
Trying to read from a text file based on a user variable entry
my entry has variations (upper/lower case) of the name "Big Fred"
The code runs but I am getting no results back.
The code on my laptop points to specific location which I have removed from the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ReadTextFileWhile
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the name you wish to search for: "); //Prompt user for the name they wish to search for
string x = Console.ReadLine(); //assign the name the user inputs as their search parameter to the value of x
StreamReader myReader = new StreamReader("C:/insert location here"); //Read the the text file at this location and assign to myReader
string line = ""; //asssign 'nothing' to line.
while (line != null) //while line in the text file is not null (empty)
{
line = myReader.ReadLine(); //pass contents of myReader to line
if (line != null && line == x) //if contents of line are not null and equal to the variable in x print to screen
Console.WriteLine(line);
}
myReader.Close(); //close myReader properly
Console.ReadLine(); //Readline to keep console window open allowing a human to read output.
}
}
}
Upvotes: 1
Views: 549
Reputation: 7341
The reason why you are getting the every line from the text file is very simple. You might have copied the text content from a web page or some where else.; and there each line is not separated by a new line constant either \n or Environment.NewLine. So what you need to d is either Open the file and after each line press Enter key to manually insert new line OR read all test from the file and Split it by Dot[.] separator and use above code to process it individually. I faced the same prob & now it is working fine.
Upvotes: 0
Reputation: 123739
You just want to match the string in caseInsensitive fashion correct. You can use .Equals
if (line.Equals(x,StringComparison.InvariantCultureIgnoreCase));
Another thing is:- You can use
String.IsNullOrWhiteSpace(line) or String.IsNullOrEmpty(line)
instead of checking if is null
Upvotes: 1
Reputation: 216313
Try with string.IndexOf and its overload that excludes case differences
line = myReader.ReadLine();
if (line != null && line.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
Console.WriteLine(line);
Upvotes: 1