Save PDF File in SQL Server Database using C#

Create table  with ID Identity column,PdfData Image, Name varchar(25)

Browse pdf file

1.bmp

Code to Save Selected PDF File

protected void btnSavePdf_Click(object sender, EventArgs e)
{
    using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Connection"].ToString()))
    {
        cn.Open();
        //Convert pdf in Binary formate
        int lenght = FileUpload1.PostedFile.ContentLength;
        byte[] data = new byte[lenght];
        FileUpload1.PostedFile.InputStream.Read(data, 0, lenght);
        using (SqlCommand cmd = new SqlCommand("insert into tblPdfData " + "(PdfData) values(@data)", cn))
        {
            cmd.Parameters.Add("@data", data);
            cmd.ExecuteNonQuery();
            Response.Write("Pdf File Save in Dab");
        }
    }
 }

Now Bind Grid View from DataBase 

2.JPG

Code Selected Index of GridView

protected void grvDisplayPdf_SelectedIndexChanged(object sender, EventArgs e)
{
    string sPathToSaveFileTo = @"C:\SelectedFile.pdf";  // on this path i will create selected PDF File Data    open pdf for checking


    //Read Connection from web config
    using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Connection"].ToString()))
    {
        cn.Open();
        using (SqlCommand cmd = new SqlCommand("select PDFData from tblpdfdata where ID='" + grvDisplayPdf.SelectedValue + "' ", cn))
        {
            using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.Default))
            {
                if (dr.Read())
                {
                    // read in using GetValue and cast to byte array
                    byte[] fileData = (byte[])dr.GetValue(0);


                    // write bytes to disk as file
                    using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                    {
                        // use a binary writer to write the bytes to disk
                        using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
                        {
                            bw.Write(fileData);
                            bw.Close();
                        }
                    }
                }


                // close reader to database
                dr.Close();
            }
        }
    }
}