Save and Read PDF File Using SQL Server and C#

Introduction

In this article we will show how to save a PDF file in a database.

First we must have a database table that contains a special field type of [varbinary](max) to contain the actual file.

Example

CREATE TABLE [dbo].[SavePDFTable](

      [ID] [int] IDENTITY(1,1) NOT NULL,

      [PDFFile] [varbinary](max) NULL

     

)

Now we must convert the PDF file into a byte array that will be put into the "PDFFile (varbinary)" field.

Code
 

protected void Button1_Click(object sender, EventArgs e)

{

 

    using (SqlConnection cn = new SqlConnection("CONNECTION STRING"))

    {

        cn.Open();

        FileStream fStream = File.OpenRead("C:\\MyFiles\\TempReport.pdf");

        byte[] contents = new byte[fStream.Length];

        fStream.Read(contents, 0, (int)fStream.Length);

        fStream.Close();

        using (SqlCommand cmd = new SqlCommand("insert into SavePDFTable " + "(PDFFile)values(@data)", cn))

       {

             cmd.Parameters.Add("@data", contents);

             cmd.ExecuteNonQuery();

             Response.Write("Pdf File Save in Dab");

       }

   }

}

To read the data:
 

protected void Button2_Click(object sender, EventArgs e)

        {

            string ToSaveFileTo = Server.MapPath("~\\File\\Report.pdf");  

                        

            using (SqlConnection cn = new SqlConnection("CONNECTION STRING"))

            {

                cn.Open();

                using (SqlCommand cmd = new SqlCommand("select PDFFile from SavePDFTable  where ID='" + "1" + "' ", cn))

                {

                    using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.Default))

                    {

                        if (dr.Read())

                        {

                          

                            byte[] fileData = (byte[])dr.GetValue(0);

                            using (System.IO.FileStream fs = new System.IO.FileStream(ToSaveFileTo, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))

                            {

                                using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))

                                {

                                    bw.Write(fileData);

                                    bw.Close();

                                }

                            }

                        }


                        dr.Close();

                        Response.Redirect("~\\File\\Report.pdf");

                    }

                }

            }

        }


 

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all
    Founded in 2012 by Red Ant Corp, Red Ant Corp & Associates Consulting (Red Ant Corp).