1

我正在制作一个也可用作记事本(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.

应用程序停止,有人可以帮助我吗?

4

1 回答 1

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
于 2012-12-05T09:23:58.057 回答