Here's a couple of functions I put together to be able to store any kind of file into a SQL Server database.
It's in Visual Basic
SQL Table
1 Doc_ID int NULL NO NULL
2 FileName nvarchar 255 NO NULL
3 FileExtention nvarchar 10 NO NULL
4 Content varbinary -1 YES NULL
Primary Function
Private Sub btn_initUpload_Click(sender As Object, e As System.EventArgs) Handles btn_initUpload.Click
Dim filePath As String = ""
Dim fInfo As FileInfo
Dim fileName As String, fileExt As String
Dim fileBinary() As Byte
Dim cn As SqlClient.SqlConnection = Nothing
Dim cmd As SqlClient.SqlCommand = Nothing
Dim procRtn As Integer
filePath = Me.txt_FilePath.Text
System.Windows.Forms.Cursor.Current = Windows.Forms.Cursors.WaitCursor
If filePath <> "" Then
fInfo = FileIO.FileSystem.GetFileInfo(filePath)
fileName = fInfo.Name
fileExt = fInfo.Extension
Try
fileBinary = Me.ConvertFileToBinary(filePath)
If SQL_Ops.ConnectToDatabase(cn) = False Then Exit Sub
If SQL_Ops.PrepCmdObject(cmd, cn, SQL_StoredProcedure.sp_saveDoc) = False Then
Call MsgBox("An error occured while accessing the stored procedure. Please contact the database administrator.", vbCritical)
cn.Close()
Throw New System.Exception("SQL Failure")
End If
cmd.Parameters("@FileName").Value = fileName
cmd.Parameters("@FileExtention").Value = fileExt
cmd.Parameters("@Content").Value = fileBinary
procRtn = cmd.ExecuteNonQuery()
If procRtn <> 0 And Err.Number = 0 Then
Me.FileList.DataBind()
Me.txt_FilePath.Text = ""
Else
Throw New System.Exception("Proc Execution Error")
End If
Catch ex As Exception
Debug.Print("File conversion failure.")
End Try
Else
'Do Nothing
End If
If Not IsNothing(cmd) Then cmd = Nothing
If Not IsNothing(cn) Then cn.Close()
System.Windows.Forms.Cursor.Current = Windows.Forms.Cursors.Default
End Sub
This is the function that will convert any file into binary data
Private Function ConvertFileToBinary(ByVal filePath As String) As Byte()
Dim fs As New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim convFile As Byte() = br.ReadBytes(CInt(fs.Length))
br.Close()
fs.Close()
Return convFile
End Function