【发布时间】:2016-11-02 08:31:44
【问题描述】:
我想用 StreamReader 和 StreamWriter 读写同一个文件。我知道在我的代码中我试图打开文件两次,这就是问题所在。谁能给我另一种方法来做到这一点?我有点糊涂了。
至于程序,我想创建一个程序,如果它不存在,我会在其中创建一个文本。如果它存在,那么它将每一行与一个列表框进行比较,并查看列表框中的值是否出现在那里。如果没有,那么它将添加到文本中。
Dim SR As System.IO.StreamReader
Dim SW As System.IO.StreamWriter
SR = New System.IO.StreamReader("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
SW = New System.IO.StreamWriter("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
Dim strLine As String
Do While SR.Peek <> -1
strLine = SR.ReadLine()
For i = 0 To Cerberus.ListBox2.Items.Count - 1
If Cerberus.ListBox2.Items.Item(i).Contains(strLine) = False Then
SW.WriteLine(Cerberus.ListBox2.Items.Item(i))
End If
Next
Loop
SR.Close()
SW.Close()
SR.Dispose()
SW.Dispose()
MsgBox("Duplicates Removed!")
【问题讨论】:
-
如果您的文件不是那么大,请考虑使用
File.ReadAllLines和File.WriteAllLines。 -
我正在研究 FileStream 命令。有点弄清楚它是如何工作的。也打开了其他可能性。
-
@ZevSpitz 谢谢,我已经知道了,但我很好奇你怎么能“以防万一”处理大文件。
标签: vb.net