Shayna Shayna - 29 days ago 9
Vb.net 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
System.IO.File.Create
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")
System.IO.File.Create(TextBox2.Text)


TextBox3.Text = FolderBrowserDialog1.SelectedPath
TextBox3.AppendText("\masterkey.txt")
System.IO.File.Create(TextBox3.Text)

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)

file.Write(RichTextBox1.Text)
file.Close()
file2 = My.Computer.FileSystem.OpenTextFileWriter(TextBox3.Text, True)
file2.Write(TextBox1.Text)
file2.Close()
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

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

System.IO.File.Create(TextBox2.Text)
System.IO.File.Create(TextBox3.Text)

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)
        file.Write(RichTextBox1.Text)
    End Using

    Using file2 As New System.IO.StreamWriter(TextBox3.Text, True)
        file2.Write(TextBox1.Text)
    End Using