用IO.StreamReader读取文件后无法写入文件

时间:2012-12-05 06:55:16

标签: vb.net filestream bufferedreader .net

我正在制作一个加密程序,它也可用作记事本(CryptoMatic)。有一个Open函数,代码如下:

    Dim r As New StreamReader(filename)
    Dim text As String = r.ReadToEnd
    txtFileContents.text = text

    r.Dispose()
    r.Close()

现在有保存并另存为按钮 保存按钮检查文件是否先前已保存。如果是,那么我试图用以下代码写入该文件:

    Dim myFileStream As New System.IO.FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None)
    myFileStream.Lock(0, 100)

    Dim myWriter As New System.IO.StreamWriter(myFileStream)
    myWriter.WriteLine(text)

    myWriter.Flush()
    myWriter.Close()
    myFileStream.Close()

    myFileStream.Unlock(0, 100)

现在当我按下保存按钮时,它会出现以下错误:

    The process cannot access the file 'C:\Users\VisualTech\Documents\Visual Studio            2010\Projects\CryptoMatic Update\CryptoMatic Update\bin\Debug\text.txt' because it is being    used by another process.

并且申请停止,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

我已经尝试过上面的代码并注意到两件事:

  • 您不需要myFileStream.Lock电话,因为您已经打开它 FileShare.None
  • 致电后,您无法拨打myFileStream.Unlock(0, 100) myFileStream.Close()

所以我以这种方式重写了你的代码。

Sub Main
    Dim text = "This is a text to write in the stream"
    Using myFileStream As New System.IO.FileStream("D:\temp\testlock.txt", FileMode.Append, FileAccess.Write, FileShare.None)
        Using myWriter As New System.IO.StreamWriter(myFileStream)
            myWriter.WriteLine(text)
        End Using
    End Using
End Sub