Introduction
When creating an application, sometimes it's useful if you want to create a recent file list as a shortcut to open a previously-opened file. This makes opening a file look simple and handy.
Using the Code
To create a recent file list, we need just three methods:
- Save file list
This method is called whenever you want to add an item to a list and save it. Usually, this item is a path to a previously-opened file.
- Load file list
This method is to load a list from file but doesn't insert it to menu. Usually, this method is called at form_load
and whenever you want to refresh list and list menu.
- Recent file click
This is a click handler when user clicks the menus. Usually, this reopens a file.
The Code
Save File List
private void SaveRecentFile(string path)
{
recentToolStripMenuItem.DropDownItems.Clear();
LoadRecentList();
if (!(MRUlist.Contains(path)))
MRUlist.Enqueue(path);
while (MRUlist.Count > MRUnumber )
{
MRUlist.Dequeue();
}
foreach (string item in MRUlist )
{
ToolStripMenuItem fileRecent = new ToolStripMenuItem
(item, null, RecentFile_click);
recentToolStripMenuItem.DropDownItems.Add(fileRecent);
}
StreamWriter stringToWrite =
new StreamWriter(System.Environment.CurrentDirectory + "\\Recent.txt");
foreach (string item in MRUlist )
{
stringToWrite.WriteLine(item);
}
stringToWrite.Flush();
stringToWrite.Close();
}
Load File List
private void LoadRecentList()
{
MRUlist.Clear();
try
{
StreamReader listToRead =
new StreamReader(System.Environment.CurrentDirectory + "\\Recent.txt");
string line;
while ((line = listToRead.ReadLine()) != null)
MRUlist.Enqueue(line);
listToRead.Close();
}
catch (Exception){}
}
Recent File Click
private void RecentFile_click(object sender, EventArgs e)
{
richTextBox1.LoadFile(sender.ToString (), RichTextBoxStreamType.PlainText);
}
And here's where those methods are called:
private void Form1_Load(object sender, EventArgs e)
{
LoadRecentList();
foreach (string item in MRUlist )
{
ToolStripMenuItem fileRecent =
new ToolStripMenuItem(item, null, RecentFile_click);
recentToolStripMenuItem.DropDownItems.Add(fileRecent);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{ ...
SaveRecentFile(openFileDialog1.FileName);
...
}
So that's it -simple but useful code.
History
- 2nd January, 2009: Initial post