2012-03-02 112 views
0

下面的代码会一次又一次地保存一个项目到文件,但是如何只保存一个项目?检查一个项目是否已经存在于一个txt文件中

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

什么是你的文本文件中的数据合同?什么规则可以依赖格式明智?每个文本行是否会总是有唯一的值? – asawyer 2012-03-02 14:30:38

+0

in listbox1 items like like“number1”,“number2”,“number3” – 2012-03-02 14:42:54

回答

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 
+0

its given error ::该方法或操作没有实施顺便说一句我用vs 2010 – 2012-03-02 14:49:40

+0

你是哪一行得到这个错误? – 2012-03-02 14:57:17

+0

它给出错误,如果不是哈希.Contains“包含”不是windowsApllication3.HasSet(字符串)的记忆 – 2012-03-02 15:35:32

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 
  1. 添加System.IO。到File.ReadAllLines
  2. 更改selectedItem设置的SelectedValue
+0

如果HashSet不起作用,则可以尝试使用List(Of String)。 – 2012-03-02 16:11:30

相关问题