Writing to file, file being used by another proces

2019-07-16 11:05发布

问题:

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.

回答1:

I suppose that the process that keep the file open is your own process.
When you call saveDialog1.OpenFile(), you are opening the file and a stream is returned.
Then you call WriteAllText() that tries to open again the same file resulting in the exception above.
You could solve simply removing the call to OpenFile()

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

Just keep in mind that WriteAllText() creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.



回答2:

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