从SQL Server保存二进制文件

时间:2010-09-11 22:59:59

标签: vb.net sql-server-2008

我正在尝试使用SaveDialog保存存储在SQL数据库中的二进制文件,函数RetrieveFile从数据库中检索指定的文件作为Byte数组,这是我到目前为止所拥有的:

Private Shared Function RetrieveFile(ByVal filename As String) As Byte()
    Dim connection As New SqlConnection("Data Source=SERVER\SQL2008;Initial Catalog=NorthPole;Integrated Security=True")
    Dim command As New SqlCommand("SELECT pcfFile FROM Items WHERE pcfFileName=@Filename", connection)
    command.Parameters.AddWithValue("@Filename", filename)
    connection.Open()
    Dim reader As SqlDataReader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)
    reader.Read()
    Dim memory As New MemoryStream()
    Dim startIndex As Long = 0
    Const ChunkSize As Integer = 256
    While True
        Dim buffer As Byte() = New Byte(ChunkSize - 1) {}
        Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
        memory.Write(buffer, 0, CInt(retrievedBytes))
        startIndex += retrievedBytes
        If retrievedBytes <> ChunkSize Then
            Exit While
        End If
    End While
    connection.Close()
    Dim data As Byte() = memory.ToArray()
    memory.Dispose()
    Return data


End Function


Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
    Dim saveFileDialog1 As New SaveFileDialog()
    saveFileDialog1.Filter = "PCF File|*.pcf|"
    saveFileDialog1.Title = "Save an pcf File"
    saveFileDialog1.ShowDialog()

    If saveFileDialog1.FileName <> "" Then
        Dim fs As System.IO.FileStream = CType(RetrieveFile("FakePCF.pcf"), System.IO.FileStream)
                    fs.Close()
    End If
End Sub

文件在数据库中保存为“SqlDbType.VarBinary”。 我得到:“索引超出了数组的范围。”于:

   Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)

MemoryStream似乎没有检索数据,但SQL sytax是正确的。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

好吧,首先,你的方法返回byte [],你正试图将它强制转换为FileStream。您应该将处理程序更改为以下内容:

Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
    Dim saveFileDialog1 As New SaveFileDialog()
    saveFileDialog1.Filter = "PCF File|*.pcf|"
    saveFileDialog1.Title = "Save an pcf File"
    saveFileDialog1.ShowDialog()

    If saveFileDialog1.FileName <> "" Then
        Dim fs As New System.IO.FileStream (saveFileDialog1.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        Dim data As Byte() = RetrieveFile("FakePCF.pcf")
        fs.Write(data, 0, data.Length)
        fs.Flush()
        fs.Close()
    End If
End Sub