How do I attach PDF files in VB.NET?
Assume that I have a Windows Forms app in which I type all the details of an employee and I need 开发者_如何学JAVAto attach his resume (which is in a PDF format) to his details. When I click the save button, all his details which he has entered can be stored into a table.
- How do I attach a PDF file into the app which the user can do by clicking a button after typing all his details?
- When the user clicks the save button, how do I save the file that has been attached by the user?
- When I retrieve the employee details, I want the file which was attached also to be displayed and shown.
Use the OpenFileDialog to allow the user to browse to the PDF they want to attach. Store the file path of the selected PDF.
When the user saves the record, read the file the user selected into a byte[]
, and save that byte[]
into a database field (probably a blob field). (See here)
To read it back in, do the reverse. Get the byte[]
out of the database, and reassemble it into a file, save the file as a temp PDF and then start a process to load it. (See here)
Here's a simple example, with no error checking, demonstrating Michael Shimmins' good suggestion.
Dim ofd As New OpenFileDialog()
'Set ofd settings'
If ofd.ShowDialog() = DialogResult.Cancel Then
Return
End If
Dim pdfData As Byte() = File.ReadAllBytes(ofd.FileName)
'Save it to your database.'
However, I suggest you consider copying the files to a file server instead of dealing with the binary data and BLOBs if you can help it. BLOBs have been known to kill database performance on some platforms. Here's one reference. Google "blob database performance" for more.
Here's an example of copying the file to a file server.
Dim newFileName As String = UniqueFileNameGeneratingFunction()
File.Copy(odf.FileName, newFileName)
'Save newFileName to your database as a string, and retrieve the file as needed'
'from the file server'
精彩评论