Write to file, file used by another process

Ok, so I can’t understand why I cannot write the file. It says that it is being used by another process. Here's the error (the IOException was unhandled):

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

Here is the current code that I use to write to a 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 checked it yesterday and it worked.

+2
source share
2 answers

Well, that’s what I ended up doing, it seems to be working fine as it is. I pulled out the if condition and left everything else as it is. I can always copy the cancellation later.

  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 code is 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 
+1
source

I believe that the process in which the file is open is your own process.
When you call saveDialog1.OpenFile (), you open the file and the stream is returned.
Then you call WriteAllText (), which tries to open the same file again, leading to the exception above.
You could just delete the OpenFile () call

  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 line to the file, and closes the file. If the target file already exists , it is overwritten.

+3
source

Source: https://habr.com/ru/post/1494730/


All Articles