简体   繁体   English

如何检查文本文件中是否已存在这些行之一?

[英]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. 我不确定在行上进行for循环是否正确。 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. 但是,我要做的是打开一个新的文本文件,以检查它是否已存在于RecentFiles(RecentFiles.txt) ,如果不存在,就不要再写了。

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: Linq非常适合:

// 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. ////以下代码仅在一行包含1个具有扩展名或任何文本的fileName时起作用。

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

Verify whether it full fill your requirement. 验证它是否完全满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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