check if string exists in a file

后端 未结 7 1694
猫巷女王i
猫巷女王i 2021-02-09 19:36

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

相关标签:
7条回答
  • 2021-02-09 20:01

    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");
                }
            }
    
    0 讨论(0)
  • 2021-02-09 20:04

    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");
        }
    }
    
    0 讨论(0)
  • 2021-02-09 20:11

    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.

    0 讨论(0)
  • 2021-02-09 20:13

    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");
    }
    
    0 讨论(0)
  • 2021-02-09 20:15

    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!

    0 讨论(0)
  • 2021-02-09 20:16

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题