Shayna Shayna - 1 year ago 107 Question

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

I've seen this answered multiple times and I think I know what the problem is but in my case the solution makes no sense to me.

I get the following error:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\llexl\Desktop\Test\Encrypted String.txt' because it is being used by another process.

I separated two parts of the code into their own buttons to troubleshoot and the first part that is responsible for creating files works just fine, but the second part of the code responsible for editing the files and renaming them is when this error happens which to me makes no sense since
shouldn't need to be closed as far as I know.

Anyways here is the code that's giving me trouble:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = FolderBrowserDialog1.SelectedPath
TextBox2.AppendText("\Encrypted String.txt")

TextBox3.Text = FolderBrowserDialog1.SelectedPath

End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim file As System.IO.StreamWriter
Dim file2 As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(TextBox2.Text, True)

file2 = My.Computer.FileSystem.OpenTextFileWriter(TextBox3.Text, True)
My.Computer.FileSystem.RenameFile(TextBox3.Text, "masterkey.perlpron")
My.Computer.FileSystem.RenameFile(TextBox2.Text, "Encrypted String.perlpron")
MsgBox("Library ready", MsgBoxStyle.Information)
End Sub

I'd appreciate some help :)

Answer Source

Just tested this and the File.Create-method is the one causing this behavior. It's not ment to be used like you are using it. Create-method opens a stream for the file and you are never closing that.

Easy fix is to remove the Create-method-call since the OpenTextFileWriter already creates the file if it does not exist.

So remove lines


And you are good to go.

Id also just use System.IO.StreamWriter with using-block to simplify the code and to be sure it's disposed properly:

    Using file As New System.IO.StreamWriter(TextBox2.Text, True)
    End Using

    Using file2 As New System.IO.StreamWriter(TextBox3.Text, True)
    End Using
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download