Search code examples
vb.netfilestreamstreamwritersavefiledialog

How to implement a SaveFileDialog in my code, where I am using a FileSteam object


so here is my code with the method, but I cannot seem to figure out how to implement a Save File Dialog within... Any information or guidance will be highly appreciated.

Private Sub btSave_Click(sender As System.Object, e As System.EventArgs) Handles btSave.Click
        If (cbPeriod.SelectedItem IsNot Nothing) Then
            Try
                Using connect As New SqlConnection(connectionString)
                    Dim command As New SqlCommand()
                    command.CommandText = selectQuery
                    command.Parameters.AddWithValue("@Period", cbPeriod.SelectedItem.ToString)
                    command.Connection = connect
                    Dim fileName As String
                    fileName = "Data.txt"
                    Dim seqNo As Integer = 0
                    Dim currDocNo As String = ""
                    Dim prevDocNo As String = ""
                    Using FileObject As New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
                        Using StreamWriterObj As New StreamWriter(FileObject)
                            connect.Open()
                            Using reader As SqlDataReader = command.ExecuteReader()
                                Dim FieldCount As Integer = reader.FieldCount - 1
                                For i = 0 To FieldCount
                                    StreamWriterObj.Write(reader.GetName(i).ToString)
                                    StreamWriterObj.Write(" @ ")
                                Next
                                StreamWriterObj.WriteLine()
                                Do While reader.Read()
                                    currDocNo = reader.GetValue(reader.GetOrdinal("ДокументNo")).ToString
                                    StreamWriterObj.Write(reader.Item(0))
                                    For i = 1 To FieldCount
                                        currDocNo = reader.GetValue(reader.GetOrdinal("ДокументNo")).ToString
                                        If (reader.GetName(i).Equals("ПореденНомер", StringComparison.InvariantCultureIgnoreCase)) Then
                                            If (currDocNo = prevDocNo) Then
                                                seqNo += 1
                                                StreamWriterObj.Write(seqNo)
                                            Else
                                                seqNo = 1
                                                StreamWriterObj.Write(" @ ")
                                                StreamWriterObj.Write(seqNo)
                                            End If
                                        Else
                                            StreamWriterObj.Write(" @ ")
                                            StreamWriterObj.Write(reader.Item(i))
                                        End If
                                    Next
                                    prevDocNo = currDocNo
                                    StreamWriterObj.WriteLine()
                                Loop
                                reader.Close()
                            End Using
                            connect.Close()
                            MessageBox.Show("Export was successful.")
                        End Using
                    End Using
                End Using
            Catch ex As SqlException
                MessageBox.Show(ex.Message.ToString)
            End Try
        Else
            MessageBox.Show("Please select a value!")
        End If
    End Sub

If you need further information let me know. As you can see I have the File object and everything so i guess i will just need to add some savefiledialog but how to get the data that the streamwriter has into the savefiledialog?


Solution

  • Use a SaveFileDialog to get a filename like this

    Dim fileName As String
    ' fileName = "Data.txt"
    Using sfd As New SaveFileDialog()
        sfd.Filter = "Text Files (*.txt)|*.txt"
        If sfd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            fileName = sfd.FileName
        Else
            Throw New Exception("User canceled out of save dialog")
        End If
    End Using
    

    Don't explicitly call Close() on your disposable objects you have wrapped in Using blocks. The Dispose method is called and it closes it for you @ End Using

    Lastly, you can remove the FileStream and use the StreamWriter to create the file as well using this constructor

    ' Using FileObject As New FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)
    ' Using StreamWriterObj As New StreamWriter(FileObject)
    Using StreamWriterObj As New StreamWriter(path:=fileName, append:=False)