最近文件的位置列表vb.net



我希望将最近的文件列表添加到我正在编写的应用程序中。我正在考虑将最近的文件添加到xml文件中。

这个文件应该存储在哪里?应该如何从代码中调用它?

我想xml将存储在安装应用程序的同一文件夹中,但并不是每个人都将应用程序安装在同一目录中。

是否有一种方法可以对其进行编码,使其始终存储在安装应用程序的同一文件夹中?

非常感谢!

下面是一个使用My.Settings的示例。它要求您打开项目属性的设置页面,并添加一个名为RecentFiles的类型为StringCollection的设置以及一个文本为"Recent"的ToolStripMenuItem

Imports System.Collections.Specialized
Public Class Form1
Private Const MAX_RECENT_FILES As Integer = 10
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadRecentFiles()
End Sub
Private Sub LoadRecentFiles()
Dim recentFiles = My.Settings.RecentFiles
'A StringCollection setting will be Nothing by default, unless you edit it in the Settings designer.
If recentFiles Is Nothing Then
My.Settings.RecentFiles = New StringCollection()
recentFiles = My.Settings.RecentFiles
End If
'Get rid of any existing menu items.
RecentToolStripMenuItem.DropDownItems.Clear()
'Add a menu item for each recent file.
If recentFiles.Count > 0 Then
RecentToolStripMenuItem.DropDownItems.AddRange(recentFiles.Cast(Of String)().
 Select(Function(filePath) New ToolStripMenuItem(filePath,
                                                 Nothing,
                                                 AddressOf RecentFileMenuItems_Click)).
 ToArray())
End If
End Sub
Private Sub UpdateRecentFiles(filePath As String)
Dim recentFiles = My.Settings.RecentFiles
'If the specified file is already in the list, remove it from its old position.
If recentFiles.Contains(filePath) Then
recentFiles.Remove(filePath)
End If
'Add the new file at the top of the list.
recentFiles.Insert(0, filePath)
'Trim the list if it is too long.
While recentFiles.Count > MAX_RECENT_FILES
recentFiles.RemoveAt(MAX_RECENT_FILES)
End While
LoadRecentFiles()
End Sub
Private Sub RecentFileMenuItems_Click(sender As Object, e As EventArgs)
Dim menuItem = DirectCast(sender, ToolStripMenuItem)
Dim filePath = menuItem.Text
'Open the file using filePath here.
End Sub
End Class

请注意,Load事件处理程序包含一段代码,以允许类型为StringCollection的设置在为其分配内容之前将为Nothing。如果您想避免在代码中执行此操作,请执行以下操作。

  1. 添加设置后,单击Value字段,然后单击带省略号(…(的按钮进行编辑
  2. 将任何文本添加到编辑器中,然后单击OK。请注意,已经添加了一些XML,其中包括您添加的项
  3. 再次单击编辑按钮(…(并删除添加的项目。请注意,XML仍然存在,但您的项已不存在

当首次加载设置时,XML代码将导致创建StringCollection对象,因此无需在代码中创建对象。

编辑:

我通过添加以下代码进行了测试:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using dialogue As New OpenFileDialog
If dialogue.ShowDialog() = DialogResult.OK Then
UpdateRecentFiles(dialogue.FileName)
End If
End Using
End Sub

我可以通过Button将十个文件添加到列表中,然后随着我添加更多文件,它们开始从列表的末尾掉下来。如果我重新添加了一个已经在列表中的,它就会移动到顶部。如果我关闭应用程序并再次运行它,列表就会一直存在。

最新更新