Error on SaveFileDialog

danyeungw

Well-known member
Joined
Aug 30, 2005
Messages
73
Programming Experience
10+
It crashed on sw = New StreamWriter(fileName). The error message was "The process cannot access the file 'C:\test.txt' because it is being used by another process". Why was wrong?
VB.NET:
Dim fileName As String = Application.StartupPath & "\Test.txt"
Dim myStream As Stream
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.RestoreDirectory = True
If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
  Dim sw As StreamWriter
  Try
    myStream = SaveFileDialog1.OpenFile()
    If (myStream IsNot Nothing) Then
      sw = New StreamWriter(fileName)
      sw.WriteLine(Me.TextBoxName.Text)
      sw.WriteLine(Me.TextBoxID.Text)
      sw.Flush()
      myStream.Close()
    End If
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  Finally
   sw.Close()
  End Try
End If
Thanks.
DanYeung
 
Last edited by a moderator:
i believe you've answered your own question, it's crashing because the file is already in use

you have the FileStream accessing the file when you try to access the file with the StreamWriter

you'll need to close the FileStream before using the StreamWriter
 
If you're trying to write to the file that the user just selected then change this:
VB.NET:
Dim sw As StreamWriter

Try
    myStream = SaveFileDialog1.OpenFile()

    If (myStream IsNot Nothing) Then
        sw = New StreamWriter(fileName)
should be this:
VB.NET:
Dim sw As StreamWriter

Try
    myStream = SaveFileDialog1.OpenFile()

    If (myStream IsNot Nothing) Then
        sw = New StreamWriter([U][B]myStream[/B][/U])
Otherwise you can forgo calling the OpenFile method altogether and just pass the FileName property to the StreamWriter constructor.
 
Back
Top