Click here to Skip to main content
15,444,490 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have tried this code but it dosent work can anyone help me with this code

What I have tried:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

       myconnection = New SqlConnection("SELECT Data FROM [pdf] WHERE id = " & TextBox1.Text & "")

       Using con As New SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=pdf;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")
           Using com As New SqlCommand("SELECT Data FROM [pdf] WHERE id = " & TextBox1.Text & "", con)
               Using reader As SqlDataReader = com.ExecuteReader()
                   While reader.Read()
                       Dim fileData As Byte() = DirectCast(reader("Data"), Byte())

                   End While
               End Using
           End Using
       End Using

   End Sub
Updated 27-Oct-20 19:15pm
Richard Deeming 29-Oct-20 13:43pm     CRLF
Using com As New SqlCommand("SELECT Data FROM [pdf] WHERE id = " & TextBox1.Text & "", con)
Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query. Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^] How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^] Query Parameterization Cheat Sheet | OWASP[^]

1 solution

You have not shared any issue with your code (does not work gives no clue to us on what issue you are facing). Looking at your code, I don't see where you define the ContentType of the binary data when you retrieve.

Refer the following article for it: Convert Binary data to PDF file in C# and VB.Net[^]

VB.NET code snippet:
Using con As New SqlConnection(constr)
    Using cmd As New SqlCommand()
        cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id"
        cmd.Parameters.AddWithValue("@Id", id)
        cmd.Connection = con
        Using sdr As SqlDataReader = cmd.ExecuteReader()
            bytes = DirectCast(sdr("Data"), Byte())
            contentType = sdr("ContentType").ToString()
            fileName = sdr("Name").ToString()
        End Using
    End Using
End Using

Try out.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900