简体   繁体   中英

How do I check if one of the lines already exist in the text file?

string filename = "";
        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFileDialog theDialog = new OpenFileDialog();
            theDialog.Title = "Open Text File";
            theDialog.Filter = "TXT files|*.txt";
            theDialog.InitialDirectory = @"C:\";
            if (theDialog.ShowDialog() == DialogResult.OK)
            {
                lines = File.ReadAllLines(RecentFiles);
                filename = theDialog.FileName;
                for (int i = 0; i < lines.Length; i++)
                {
                    recentfiles = new StreamWriter(RecentFiles, true);
                    recentfiles.WriteLine(theDialog.FileName);
                    recentfiles.Close();
                    items = File
                        .ReadLines(RecentFiles)
                        .Select(line => new ToolStripMenuItem()
                        {
                            Text = line
                        })
                        .ToArray();
                recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
                }

                TextFileContentToRichtextbox(filename);
            }
        }

I'm not sure if doing the for loop over the lines is right. But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.

Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.

Linq is perfect for this:

// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
    // then write it into recent files text file
}

//// the below code will work only if a line has 1 fileName with extension or any text.

if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
                    { 
    //// lines contains
                    }
                else
                {
    ////lines doesnot contain file name
                }

Verify whether it full fill your requirement.

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