每次打开表单时节省数组的时间

时间:2013-10-28 22:25:02

标签: vb.net visual-studio visual-studio-2012

我有以下代码:

Public Class MyAccount

Dim FileName As String = Application.StartupPath & "\myarray.txt"
Dim AccessLog() As String

Private Sub MyAccount_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.Items.Clear()
    AccessLog = File.ReadAllLines(FileName)
    ListBox1.Items.AddRange(AccessLog)
    ListBox1.Items.Add("Last Login: " + DateTime.Now.ToLongTimeString())
    IO.File.WriteAllLines(FileName, ListBox1)
    ListBox1.Refresh()
End Sub

End Class

我对此代码的目标是,每次打开MyAccount()窗体时,它都会将一条记录添加到列表框中,然后将其保存到文本文件中,以便在应用程序关闭后保留。但是,我不确定我是以最好的方式做到这一点,而且我收到的错误是“文件未被声明。它可能因其保护级别而无法访问”:

AccessLog = File.ReadAllLines(FileName)

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

使用:

System.IO.File.ReadAllLines 

或导入以下命名空间:

System.IO.

答案 1 :(得分:0)

使用ListBox.Items集合写入文件。一种方法是使用LINQ:

Private Sub MyAccount_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.Items.Clear()
    AccessLog = File.ReadAllLines(FileName)
    ListBox1.Items.AddRange(AccessLog)
    ListBox1.Items.Add("Last Login: " + DateTime.Now.ToLongTimeString())
    IO.File.WriteAllLines(FileName, ListBox4.Items.Cast(Of String)().ToArray)
    ListBox1.Refresh()
End Sub

答案 2 :(得分:0)

使用List(Of String)来保持行,然后你可以添加" Last Login"在将其写回文件之前将其值赋予它:

Public Class MyAccount

    Dim FileName As String = System.IO.Path.Combine(Application.StartupPath, "myarray.txt")
    Dim AccessLog As New List(Of String)

    Private Sub MyAccount_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If System.IO.File.Exists(FileName) Then
            AccessLog.AddRange(System.IO.File.ReadAllLines(FileName))
            ListBox1.Items.AddRange(AccessLog.ToArray)
            ListBox1.Items.Add("Last Login: " + DateTime.Now.ToLongTimeString())
        End If
        AccessLog.Add(DateTime.Now.ToLongTimeString())
        System.IO.File.WriteAllLines(FileName, AccessLog)
    End Sub

End Class

如果您不需要Load()事件之外的List()中的数据,则将它们声明为本地,以便它们被垃圾收集。您仍然可以访问ListBox中的值。只取决于你对该信息做了什么......