2014-01-18 159 views
0

我有一个程序,我正在创建,当我去删除空行这是我如何去做。如何从文本文件中删除空白行? vb.net?

For Each i As ListViewItem In lvSongs.SelectedItems 
     lvSongs.Items.Remove(i) 
     CurrentSong = i.SubItems(4).Text 'This is the Songs Path 

     files = File.ReadAllText("songs.txt") 'The songs path's are in the txt 


     'I am using this as a list of lines i want to keep in 
     'the txt file. 
     Dim linesToKeep As New List(Of String) 

     For Each line As String In files 'Goes through lines 
      If Not line.Contains(CurrentSong) Then 'checks to see if line is Current song 
       linesToKeep.Add(line)    'Adds line if its not CurrentSong to the list 
      End If 
     Next 


     File.WriteAllLines("songs.txt", linesToKeep.ToArray()) 

但是当我去检查的txt文件,我得到这个:

实例(但横写,每个字母作为一个新行)

在文本文件我的朋友说:因为我把行设置为字符串而不是字符串()。

感谢您的帮助! 询问更多的信息,如果我很困惑你...

回答

1

问题是你正在使用ReadAllText API。这会返回String而不是String(),因此当您稍后迭代时,您会遍历文件中的每个字符,而不是每行。为了解决这个问题使用ReadAllLines API返回一个String()

files = File.ReadAllLines("songs.txt") 

注意我不能告诉如果files是隐式声明的本地或外地。如果输入的字段为String,则需要将其类型更改为String()

+0

哇,非常感谢。另外,谢谢你解释得非常好。我一直在做vb.net一段时间现在信不信由你。毕竟这一次我无法弄清楚String和String()之间的区别是什么。 – ShaneRibz