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.
我不确定是否在线上进行for循环是正确的。但我想要做的是当我打开一个新的文本文件来检查它是否已经存在于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.
循环遍历行,如果循环遍历所有行并且变量filename不存在,则将其写入文本文件,然后更新项目。
2 个解决方案
#1
2
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
}
#2
1
//// the below code will work only if a line has 1 fileName with extension or any text.
////以下代码仅在行有1个带扩展名的文件名或任何文本时才有效。
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.
验证是否满足您的要求。
#1
2
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
}
#2
1
//// the below code will work only if a line has 1 fileName with extension or any text.
////以下代码仅在行有1个带扩展名的文件名或任何文本时才有效。
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.
验证是否满足您的要求。