mercredi 29 août 2018

Check if text exists in textfile c#

im trying to figure out if the text url that I get from current url exists in 'linkx.txt', if it does then show message, if it doesn't then write to text file. however, when i run this code program writes to text file twice before recognizing the text exists.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
            {
                string url = "";
                if (keyData == Keys.F1) { Application.Exit(); return true;   }
                else if (keyData == Keys.F2) { url = webBrowser1.Url.AbsoluteUri; }

                    using (StreamReader sr = File.OpenText("linkx.txt"))
                    {
                        string texxt = url;
                        string[] lines = File.ReadAllLines("linkx.txt");
                        bool matched = false;
                        for (int x = 0; x < lines.Length - 1; x++)
                        {
                            if (texxt == lines[x])
                            {
                                sr.Close();
                                MessageBox.Show("there is a match");
                                matched = true;
                            }
                        }
                        if (!matched)
                        {
                            sr.Close();
                            using (StreamWriter wriite = File.AppendText("linkx.txt"))
                            {
                                wriite.WriteLine(url);
                                MessageBox.Show("url copied!");
                                return true;    // indicate that you handled this keystroke
                            }
                        }
                    }
                // Call the base class
                return base.ProcessCmdKey(ref msg, keyData);
            }

Aucun commentaire:

Enregistrer un commentaire