[英]Unable to read multiple lines in text file vb.net
我不确定我做错了什么我试图读取一个文本文件,其中包含许多带有文件名和扩展名的文件路径。 我已设法拆分文件路径和文件名以添加到我的字典中,然后将其添加到列表框中。
问题是我的代码重复读取同一行。 任何人都可以就我哪里出错提供建议。 文本文件格式为...
C:\\Users\\User\\Desktop\\Music track3@01。 Aerosmith & Run DMC - Walk This Way (1986).mp3 C:\\Users\\User\\Desktop\\Music track3@01。 INXS - 今晚我需要你 (1988).mp3
我使用@char 来帮助分隔文件路径和名称。
Dim lines = File.ReadAllLines("tmp.txt")
'read from a file
Dim line As String
Using reader As New StreamReader("tmp.txt")
line = reader.ReadLine()
Dim str = line
Dim split = str.Split("@")
Dim FilePathValue As String
Dim FileNameKey As String
If (split.Count = 2) Then
FilePathValue = split(0).ToString()
FileNameKey = split(1).ToString()
'
End If
' Load items into the music dictionary
For i = 0 To lines.Length - 1 Step 2
MsgBox("Path should not be blank??? = " &
FilePathValue & " File Name = " & FileNameKey)
MusicDictionary.Add(FileNameKey(i), FilePathValue(i))
UpdateTheDictionary()
Next
'Here we need to load the filename into the dropdown items
For Each item In MusicDictionary
'Dim x =
MusicToolStripMenuItem.DropDownItems.Add(item.Key)
'AddHandler x.Click, AddressOf ToolMenuItem_Click
Next
End Using
谢谢
你读了你的文件两次:
您将文件读入数组
Dim lines = File.ReadAllLines("tmp.txt")
然后你也开始再次阅读,这次是以“逐行”的方式,但你只阅读了第一行:
Using reader As New StreamReader("tmp.txt")
line = reader.ReadLine()
您处理第一行,提取文件名等,然后通过循环读取的数组在同一行上重复操作:
For i = 0 To lines.Length - 1 Step 2
希望你能理解你的第一条指令是读取文件的所有行,将它们读入内存的一个数组中,然后再次读取第一行将另一个变量放在内存的不同部分,绝对没有链接在这两项数据之间。 循环遍历数组不会改变line
变量的内容(也不会再次执行拆分等)
该怎么办?
删除现有的 for 循环,并将 Using 替换为For Each line in lines
的For Each line in lines
,然后调试结果。 要调试,请将光标放在代码的第一行,按 F9 使其变为红色,然后运行程序。 当所有内容在第一行以黄色标记停止时,您可以使用调试菜单上的 Step Over/Into/Out 命令来浏览代码(使用它们的快捷键,更容易)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.