我正在制作一个加密程序,该程序也可以用作记事本(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:UsersVisualTechDocumentsVisual Studio 2010ProjectsCryptoMatic UpdateCryptoMatic UpdatebinDebugtext.txt' because it is being used by another process.
并且应用程序停止,任何人都可以帮助我吗?
我已经尝试了上面的代码,并注意到两件事:
- 您不需要
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:temptestlock.txt", FileMode.Append, FileAccess.Write, FileShare.None)
Using myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine(text)
End Using
End Using
End Sub