Home > Mobile >  text file im trying to overwrite is being used by another process, but it is not in use?
text file im trying to overwrite is being used by another process, but it is not in use?

Time:02-01

im trying to overwrite a text file saved on an external drive using an openfile dialog in vb.net winforms, and i keep getting the error: System.IO.IOException: 'The process cannot access the file 'F:\SETTINGS.TXT' because it is being used by another process.' after clicking the save button, i get the error.

here is my code: ` Public Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click

    Dim myStream As Stream
    Dim FileSaveLocation As String
    Dim openFileDialog1 As New OpenFileDialog()

    openFileDialog1.Filter = "txt files (*.txt)|*.txt"
    openFileDialog1.FilterIndex = 2

    If openFileDialog1.ShowDialog() = DialogResult.OK Then
        myStream = openFileDialog1.OpenFile()
        FileSaveLocation = openFileDialog1.FileName
        MessageBox.Show(FileSaveLocation)
        If (myStream IsNot Nothing) Then
            Dim file As System.IO.StreamWriter
            IO.File.WriteAllText(FileSaveLocation, "SETTINGS.txt")
            file.WriteLine("list of variables and text go here, hidden for privacy" ,True)
            File.Close()
        End If
    End If
End Sub`

ive been switching around the code and slowly making my way through different issues and errors, i thought maybe it has a strange error with the messagebox but removing that makes no difference, but im really stumped on this one, can anyone help? thanks a tonne in advance, its hurting my brain XD

CodePudding user response:

You're opening the file...

myStream = openFileDialog1.OpenFile()

... and then calling WriteAllText which tries to open the file as well...

IO.File.WriteAllText(FileSaveLocation, "SETTINGS.txt")

If you truly do need to open the file to evaluate some condition before you write then you'll need to be sure to close myStream before the call to WriteAllText

  • Related