-1

I have this code to write some data from textboxes into a textfile. And i'm using streamwriter to do this. Here you may see the code below:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim Save As New SaveFileDialog()
        Dim myStreamWriter As System.IO.StreamWriter
        Save.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
        Save.CheckPathExists = True
        Save.Title = "Export & Save - FNG"
        Save.FileName = txtTitle.Text & " - Plugs Details File Exported"
        Save.ShowDialog(Me)
        Try

            myStreamWriter = System.IO.File.AppendText(Save.FileName)
            myStreamWriter.Write("Details of Plugs:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
            myStreamWriter.Flush()
        Catch ex As Exception
        End Try


    End Sub

The code does work fine, it saves the details into a text file too. But the problem is when i cancel the save file dialog (without saving the textfile) it stil creates a file in the application start path. Why is this happening? What am i doing wrong? How do i correct this?

Jeff
  • 17
  • 1
  • 6
  • 1
    Don't ever use Try/Catch like that. You are simply ignoring any exceptions, but whatever problems may have caused the exceptions are not going away! Further, you will not know what these problems are, since you have ignored them! – John Saunders Feb 02 '14 at 22:42
  • @JohnSaunders i removed the Try/Catch and debugged and still nothing is popping up as an error and yet the file still saves even if i do not save the file (even when i close the save file dialog) :/ – Jeff Feb 02 '14 at 22:48
  • See my answer: why do you think that cancelling the Save would make your Sub return? – John Saunders Feb 02 '14 at 22:50
  • In addition, as you can see in the code, the save dialog file extensions i'm using is `*.txt"` but the file that's being created after i close the save file dialog without saving is not having any extension. It creates a file like this http://gyazo.com/cf1c560a8934f8bf5979c30cef26bd28.png – Jeff Feb 02 '14 at 22:58

1 Answers1

1

Try

If Save.ShowDialog(Me) <> DialogResult.Ok Then Return

Cancelling the dialog doesn't automatically make your Sub return!

Further, you are using StreamWriter wrong. Use

Using myStreamWriter As System.IO.StreamWriter = System.IO.File.AppendText(Save.FileName)
        myStreamWriter.Write("Details of Pish flaps:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
End Using

And remove the Dim of the StreamWriter. This will ensure that the StreamWriter is closed even if an exception is thrown.

John Saunders
  • 160,644
  • 26
  • 247
  • 397