Coder Guy
Coder Guy

Reputation: 49

Cannot write to a file after reading it with IO.StreamReader

I am making an encryption program that also functions as a notepad (CryptoMatic). There is a Open function with the following code:

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

    r.Dispose()
    r.Close()

Now there is the save and save as button the save button checks if the file had been saved previously or not. If yes then I am trying to write to that file with the following code:

    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)

Now when i press the save button it gives the following error:

    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.

and the application stops, can anyone please help me?

Upvotes: 1

Views: 1381

Answers (1)

Steve
Steve

Reputation: 216353

I have tried your code above and have noticed two things:

  • You don't need a myFileStream.Lock call because you already open it with FileShare.None
  • You can't call myFileStream.Unlock(0, 100) after the call to myFileStream.Close()

So I have rewritten your code in this way.

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

Upvotes: 1

Related Questions