0

我有以下代码:

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)

任何帮助将不胜感激。

4

3 回答 3

1

要么使用:

System.IO.File.ReadAllLines 

或者导入以下命名空间:

System.IO.
于 2013-10-28T22:27:14.930 回答
0

Use a List(Of String) to hold the lines, then you can add the "Last Login" value to it as well before writing it back out to the file:

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

If you don't need that data in the List() outside of the Load() event then declare them as locals so they get garbage collected. You can still access the values in the ListBox. Just depends on what you're doing with that info...

于 2013-10-28T23:51:55.923 回答
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
于 2013-10-28T23:41:46.023 回答