以下代码会一次又一次地将项目保存到文件中,但如何只保存一次项目?
Dim w As New IO.StreamWriter("E:\test.txt", True)
w.WriteLine(ListBox1.SelectedItem, True)
w.Close()
例如,如果number1
已经保存在txt文件中,那么如何使用以下内容重新保存?
dim exist As IO.FileAccess ("e:\s.txt")
if exist.that.item.is.exist= true then
w.WriteLine(ListBox1.SelectedItem, True)
else
msg "that item is already in your txt file "
end if
例如listbox1
个项目是:
“数字1”
“数字2”
“number3的”
“4号”
我正在使用VS 2010。
答案 0 :(得分:1)
Dim hash As HashSet(Of String) = New HashSet(Of String)(File.ReadAllLines("E:\test.txt"))
If Not hash.Contains(ListBox1.SelectedItem.ToString()) Then
Dim w As New IO.StreamWriter("E:\test.txt", True)
w.WriteLine(ListBox1.SelectedItem, True)
w.Close()
Else
'Item is already in text file
End If
答案 1 :(得分:0)
试试这个。这是@Diego代码,有一些细微的变化。 (我还没有编辑权限)
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("E:\test.txt"))
If Not hash.Contains(ListBox1.SelectedValue) Then
Dim w As New IO.StreamWriter("E:\test.txt", True)
w.WriteLine(ListBox1.SelectedValue, True)
w.Close()
Else
'Item is already in text file
End If