Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm so close with this but the last section of this is driving me insane. I have a txt file that is read by this code, and if it fails to find the string in the file, I want it to return a string once saying "string not found".

However the current code (below) returns "string not found" for each line the string isn't found, which is not what I'm after. I want it to read through the whole document and return it once when the string isn't found. Any ideas?

C#
int counter = 0;
string dt;

StreamReader file = new StreamReader(path);

while ((dt = file.ReadLine()) != null)
{
    if (dt.Contains(thisLetter))
    {
        thisType = dt;
    }
    else
    {
		Console.WriteLine("string not found");
		// Returns for every single line of the file that doesn't contain string. Which is not what I'm after.
		// Want it to return once on not finding string in file.
    }
    counter++;
	
file.Close();


What I have tried:

Have tried adding in addition code to check document for the string but it does not have the desired effect the ways I've done it.
Posted
Updated 5-May-22 4:10am
Comments
Graeme_Grant 5-May-22 9:31am    
[moved]
[no name] 5-May-22 9:55am    
[removed spam]

"I want it to return a string once saying "string not found""

The check then should be outside the loop after you finish reading.
 
Share this answer
 
Solution using a bool variable,
int counter = 0;
string dt;
bool isFound = false;

StreamReader file = new StreamReader(path);

while ((dt = file.ReadLine()) != null)
{
    if (dt.Contains(thisLetter))
    {
        isFound = true;
        thisType = dt;
    }
    counter++;
}
if(!isFound)
{
    Console.WriteLine("string not found");
}
file.Close();
 
Share this answer
 
v2
The simplest solution is this:
string dt;

using (StreamReader file = new StreamReader(path))
   {
   while ((dt = file.ReadLine()) != null)
      {
      if (dt.Contains(thisLetter))
         {
         thisType = dt;
         return;
         }
      }
   Console.WriteLine("string not found");
   }
 
Share this answer
 
Comments
Rajeev Jayaram 5-May-22 10:15am    
Good one!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900