简体   繁体   中英

check if string exists in a file

I have the following piece of code which opens a text file and reads all the lines in the file and storing it into a string array.

Which then checks if the string is present in the array. However the issue I'm facing is that whenever a string is found, it always shows "there is a match" as well as "there is no match". Any idea how to fix this?

check this code:

using (StreamReader sr = File.OpenText(path))
{
    string[] lines = File.ReadAllLines(path);
    for (int x = 0; x < lines.Length - 1; x++)
    {
        if (domain == lines[x])
        {
            sr.Close();
            MessageBox.Show("there is a match");
        }
    }
    if (sr != null)
    {
        sr.Close();
        MessageBox.Show("there is no match");
    }
}

Sounds overly complex, no reason to check by line or anything if you want to know if a string is present in a file. You can replace all of your code simply with :

if(File.ReadAllText(path).Contains(domain))
{
    MessageBox.Show("There is a match");
}

I would recommend seting and flag and checking it as follows...

using (StreamReader sr = File.OpenText(path))
{
    string[] lines = File.ReadAllLines(path);
    bool isMatch = false;
    for (int x = 0; x < lines.Length - 1; x++)
    {
        if (domain == lines[x])
        {
            sr.Close();
            MessageBox.Show("there is a match");
            isMatch = true;
        }
    }
    if (!isMatch)
    {
        sr.Close();
        MessageBox.Show("there is no match");
    }
}

Good Luck!

Actually you don't need to read whole file into memory. There is File.ReadLines method which allows you enumerate file lines one by one, without reading whole file. You can create following method

private bool DomainExists(string domain)
{
    foreach(string line in File.ReadLines(path))
        if (domain == line)
            return true; // and stop reading lines

    return false;
}

Usage of this method looks like:

if (DomainExists(domain))
    MessageBox.Show("there is a match");
else
    MessageBox.Show("there is no match");

Also two side notes - you don't need StreamReader if you are reading lines with File.ReadAllLines (it creates reader internally). Just check - you even don't use sr variable anywhere. And second note - you don't need to manually close stream, if you wrapped it in using block. In that case stream will be disposed and closed automatically.

Simplest way:

string content = File.ReadAllText(path);
if (content.IndexOf(domain) > -1)
{
   // domain exists
}
else
{
   // domain does not exist
}

and now to analyze your code:

1st, you are creating StreamReader instance, but you don't use it later in your code.

2nd, what if domain name has multiple occurrence in the file? In your code you will get multiple 'there is a match' in your code.

using (StreamReader sr = File.OpenText(path)) // you can remove this line
{
    string[] lines = File.ReadAllLines(path); // as you are not using it here
    for (int x = 0; x < lines.Length - 1; x++)
    {
        if (domain == lines[x])
        {
            sr.Close();
            MessageBox.Show("there is a match");
            hasMatch = true;
            break; // exit loop if found
        }
    }

    if (!hasMatch)
    {
        // there is no match
    }

    if (sr != null) // you dont need this if you remove it from the beginning of the code
    {
        sr.Close();
        MessageBox.Show("there is no match");
    }
}

You can try this:


First you need to create a method that receives an array of type string, then we convert that array to a string, then we read all the text from the txt and we can use ( Contains ) to know if the text we send exists in our txt and we validate if that is truth or false, I hope it helps you.

        public static void TextValidation(string[] val){
            //Path of your file
            string path = "/Users/Desktop/YourFile.txt";
            //Array to string
            string b = string.Join(",",val);
            //Validate if exists
            if(File.ReadAllText(path).Contains(b)){
                Console.WriteLine("found");
                // Do something if the data is found
            }else{
                Console.WriteLine("Not found");
            }
        }

Due to the accepted answer not fixing the problems in the original question here is a short and sweet LINQ based version:

private static bool TextFoundInFile(string fileName, string text)
{
    // If the line contains the text, FirstOrDefault will return it. 
    // Null means we reached the end without finding it.
    return File.ReadLines(fileName).FirstOrDefault(x => x.Contains(text)) is not null;
}

The benefit to this method is that it returns true right when it finds the value. It will only read the entire file if the text is not found. This can have performance improvement if you are working with large files that normally contain your search.

You could try this code:

 using (StreamReader sr = File.OpenText(path))
                        {
                            string[] lines = File.ReadAllLines(path);
                            for (int x = 0; x < lines.Length - 1; x++)
                            {
                                if (lines[x].Contains(domain, StringComparison.InvariantCultureIgnoreCase)
                                {
                                    sr.Close();
                                    MessageBox.Show("there is a match");
                                }
                            }
                            if (sr != null)
                            {
                                sr.Close();
                                MessageBox.Show("there is no match");
                            }
                        }

Try try catch:

string x;

string log = @"C:\Users\Log.txt";

string ruta = @"C:\Users\x.txt";

if (File.Exists(ruta))
{                    
    try
    {
        x = File.ReadAllText(ruta);  
    }
    catch (Exception ex)
    {
        File.AppendAllText(ruta, "Something");
        File.AppendAllText(log, Environment.NewLine + DateTime.Now.ToString() + ": The file not contain a string. " + ex.Message);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM