Reputation: 129
In the top of form1:
StreamWriter recentfiles;
string[] lines;
string line = null;
int line_number = 0;
string RecentFiles = "";
In the constructor:
RecentFiles = @"e:\RecentFiles.txt";
if (!File.Exists(RecentFiles))
{
recentfiles = new StreamWriter(RecentFiles);
recentfiles.Close();
}
else
{
lines = File.ReadAllLines(RecentFiles);
items = File
.ReadLines(@"e:\RecentFiles.txt")
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
}
for (int i = 0; i < items.Length; i++)
{
if (!File.Exists(items[i].Text))
{
using (StreamReader reader = new StreamReader(RecentFiles))
{
using (StreamWriter writer = new StreamWriter(RecentFiles))
{
while ((line = reader.ReadLine()) != null)
{
line_number++;
if (line_number == i)
continue;
writer.WriteLine(line);
}
}
}
}
}
In the text file RecentFiles for example in the first line I have:
d:\test.txt
In the second line:
e:\test\test.txt
What I want to do is that if one of the files in the text file is not exist remove it delete it from the RecentFiles.txt
But I'm getting exception on the line:
using (StreamWriter writer = new StreamWriter(RecentFiles))
The process cannot access the file 'e:\RecentFiles.txt' because it is being used by another process
How can i solve it ?
Upvotes: 1
Views: 70
Reputation: 117084
It seems to me that this does what you need:
File.WriteAllLines(RecentFiles,
File.ReadAllLines(RecentFiles)
.Where(f => File.Exists(f)));
Upvotes: 0
Reputation: 9001
just make it better:
lines = File.ReadAllLines(RecentFiles);
List< ToolStripMenuItem > items = new List< ToolStripMenuItem >();
using (StreamWriter writer = new StreamWriter(RecentFiles))
{
for (int i = 0; i < lines.Length; i++)
{
if (File.Exists(lines[i])) {
writer.WriteLine(lines[i]);
items.Add(new ToolStripMenuItem()
{
Text = lines[i]
});
}
}
}
Upvotes: 2