写入文件时文件已打开时出错

时间:2014-02-06 00:46:57

标签: vb.net

我有一个表单,其中包含我保存到文本文件的字段。

在同一表格上,我有一个按钮,可让您查看之前从该文本文件中保存的内容

当我点击按钮时,它会读取文本文件并显示在数据网格上。

此代码显示给datagrid

Dim reader As StreamReader
    reader = New StreamReader("C:\Users\John\Desktop\tickets.txt")
    Dim a As String
    Dim results() As String
    Do
        a = reader.ReadLine
        results = a.Split(vbTab)
        dgv.Rows.Add(results(0), results(1), results(2), results(3), results(4), results(5))
        ' Code here
        '
    Loop Until a Is Nothing

    reader.Close()
    reader.Dispose()

此代码保存到文件

 Dim file As StreamWriter
    file = New StreamWriter("C:\Users\John\Desktop\tickets.txt", True)
    file.WriteLine(txtname.Text & vbTab & dtdate.Text & vbTab & txttime.Text & vbTab & txtwho.Text & vbTab & txtproblem.Text & vbTab & txtresolution.Text)
    file.Close()

当我首先读取记录然后尝试保存它们时我不断收到错误,该进程无法访问该文件,因为它正由另一个进程使用。

我关闭了读者和作者,并且不确定为什么会发生这种情况

1 个答案:

答案 0 :(得分:1)

更好的代码,你确定你的循环结束了吗?

写:

Dim path As String = "C:\Users\John\Desktop\tickets.txt"
If File.Exists(path) Then
 Using sw As New StreamWriter(path, True)
  'code
 End Using' closes and disposes for you
End If

读:

Dim path As String = "C:\Users\John\Desktop\tickets.txt"
If File.Exists(path) Then
 Dim results As New List(Of String)
 Using sr As New StreamReader(path)
  While Not sr.EndOfStream()
   results.Add(sr.Readline())
   'better than do loop
  End While
 End Using' closes and disposes for you
End If

For Each line In results
  'add to DGV
Next