LBPLC
LBPLC

Reputation: 1571

Retrieve Access Attachments Via VB.NET

I have some code that will insert attachments to a newly added record in a database:

If Attachfile = True Then
            Me.Job_RecordsTableAdapter.Fill(Me.Database_Job_RecordsDataSet.Job_Records)
            ' Form1.JobRecordsBindingSource.AddNew()

            Me.DataGridView1.Sort(Me.DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Descending)

            Dim fd As OpenFileDialog = New OpenFileDialog()
            Dim strFileName As String

            fd.Title = "Open File Dialog"
            fd.InitialDirectory = "C:\"
            fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
            fd.FilterIndex = 2
            fd.RestoreDirectory = True
            fd.Multiselect = True


            If fd.ShowDialog() = DialogResult.OK Then



                For Each file As String In fd.FileNames

                    strFileName = file

                    Dim dbe As New DBEngine
                    Dim db As Database = dbe.OpenDatabase(Fpath)
                    Dim rstRecord As Recordset = db.OpenRecordset( _
                            "SELECT * FROM [Job Records] WHERE [Job Record]=" & DataGridView1.Rows(0).Cells(0).Value, _
                            RecordsetTypeEnum.dbOpenDynaset)
                    rstRecord.Edit()
                    Dim rstAttachments As Recordset2 = rstRecord.Fields("Attachments").Value
                    rstAttachments.AddNew()
                    Dim AttachmentData As Field2 = rstAttachments.Fields("FileData")
                    AttachmentData.LoadFromFile(strFileName)
                    rstAttachments.Update()
                    rstAttachments.Close()
                    rstRecord.Update()
                    rstRecord.Close()
                    db.Close()

                Next
            End If
        End If

This code works perfectly for what I need it to do. But I need some code to do the reverse and allow me to open the files from the database, in a very similar fashion to how Access will let you open the files if you double click on the attachment field.

I have searched and not really found any examples of this, everyone either links to a microsoft page which has been removed, or gives VBA code for inside access to dump all the attachments, which isn't what I want.

Does anyone have any ideas?

Upvotes: 0

Views: 1336

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123409

To retrieve an attachment you want to use the .SaveToFile method of an Access DAO Field2 object, similar to the .LoadFromFile method in your question's example code. See my other answer here for details.

Upvotes: 1

Related Questions