我创建了一个加载文本文件的程序,应该加载文本文件中的所有行并在listview中显示它们
但是它只加载listview中的第一行如何让它读取整个文件?
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
Dim Path As String = OpenFD.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
Dim lv As New ListViewItem
For Each Line As String In ItemLines.Lines
List.Items.Add(lv)
lv.Text = Line
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
Next
Catch ex As Exception
End Try
End Sub
答案 0 :(得分:1)
一种可能的解决方案可能如下所示:
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
' full path to the file + name
Dim filename As String = OpenFD.FileName
Try
' check if file exists to prevent errors
if (File.Exists(filename)) then
' fetch complete text into as lines
Dim Lines = File.ReadAllLines(filename)
' iterate over each line
For Each Line As String In Lines
Dim lv as new ListViewItem
' take it
lv.Text = Line
' and use it
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
' show it
List.Items.Add(lv)
Next
end if
Catch ex As Exception
' inform the user resp. developer
Console.WriteLine(String.Format("An error occurred: {0}", ex.Message))
End Try
End Sub
如前所述,如果您想逐行阅读文件并且不要禁止错误,请使用File.ReadAllLines - 告知用户或至少开发人员(您自己,使用日志文件或适当的内容)