Search code examples
vb.netvisual-studio-2010writefile

Writing to file, file being used by another process


Alright, so I can't figure out why I can't write to a file. It says it's being used by another process. Here's the error (IOException was unhandled):

The process cannot access the file 'C:\Temp\TempFile.cfg' because it is being used by another process.

Here's the current code I'm using to write to the file:

Dim myConfig
    Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "Configuration Files (*.cfg)|*.cfg"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        myConfig = saveFileDialog1.OpenFile()
        If (myConfig IsNot Nothing) Then
            System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
            myConfig.Close()
        End If
    End If

I'm not sure what I am missing as I thought I tested this yesterday and it worked.


Solution

  • Well here's what I ended up doing, seems to be working just fine as is. I took out the if condition and left everything else as is. I can always code for the cancel later on.

        Dim myConfig
        Dim saveFileDialog1 As New SaveFileDialog()
    
        saveFileDialog1.Filter = "Configuration Files (*.cfg)|*.cfg"
        saveFileDialog1.FilterIndex = 2
        saveFileDialog1.RestoreDirectory = True
    
        System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
    

    This codes for the ok/cancel button.

        If saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
        End If