使用vb.net检索存储在sql server中的excel文件

时间:2012-01-09 17:34:15

标签: sql-server vb.net

我有一个使用vb.net的桌面应用程序,用于处理一些excel文件,这些文件存储在sql server数据库中。 这是我的代码:

Try
        conDCS.Open()
        comDCS.Connection = conDCS
        comDCS.CommandType = CommandType.Text
        comDCS.CommandText = "select top 2 [Filename], [File] " & _
                            "from tblFiles (nolock) " & _
                            "where ([Filename] like 'DIG%' or [Filename] like 'FAC%') and " & _
                            "(UploadDate>='" & FromDate & "' and UploadDate<'" & ToDate & "')"
        comDCS.ExecuteNonQuery()
        rdrDCS = comDCS.ExecuteReader
        If rdrDCS.HasRows Then
            While rdrDCS.Read
                Dim imageInBytes As Byte() = rdrDCS(1)
                Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream(imageInBytes, False)
                Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(memoryStream)
                image.Save(TempPath & rdrDCS(0))
            End While
            ToProcess = True
        End If
        rdrDCS.Close()
    Catch ex As Exception
        ToProcess = False
        MessageBox.Show("Error accessing to the files: " & ex.Message)
    Finally
        conDCS.Close()
    End Try

我得到:“参数无效”在这一行:

Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(memoryStream)

我已经明白这个错误与无效的图像数据有关,但我无法弄清楚可能是什么问题。

imageInBytes的长度为41473.数组中的某些项目的值为零。

这里可能有什么问题,或者也许,任何人都可以提供有效的代码来实现这个目标吗?

1 个答案:

答案 0 :(得分:3)

我们使用常用方法将文件从数据库字段保存到文件:

Public Function FieldToFile(ByVal sFileName As String, ByVal theField As Object) As Boolean
    ' Exceptions are handled by the caller

    If theField IsNot DBNull.Value Then
        Using oStream As New System.IO.FileStream(sFileName, IO.FileMode.Create, IO.FileAccess.Write)
            If oStream IsNot Nothing Then
                Dim aBytes As Byte()

                aBytes = DirectCast(theField, Byte())

                oStream.Write(aBytes, 0, aBytes.Length)
                oStream.Close()
            End If
        End Using
    End If

    Return True
End Function

可以这样调用:

Call FieldToFile(someFileName, rdrDCS(1)