How to Save or Read PDF or any File to or from a varbinary column in Sql Server - simplest C# code

Hi Guys, This post is a continuation to my earlier post where I wrote about searching for text in pdf files, In my earlier post I had shared query to insert the pdf's using Sql Server Open Rowset.

This post will explore saving and retrieving pdf files to or from a database table - In this sample code I have hard coded the values for better understanding, in real time we fetch these values from a database table or an excel.

The below code is for a Console Application -
Here the column "fileContent" is of type varbinary.

C# Code to Store PDF Files into Database
using System;
using System.Data.SqlClient;
using System.IO;

namespace CSharpConceptsDemo
{
    class PDFFilesLoadIntoDB
    {
        static void Main2(string[] args)
        {
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            string credentials = System.Configuration.ConfigurationManager.ConnectionStrings["SqlDBkey"].ToString();
            using (SqlConnection cn = new SqlConnection(credentials))
            {
                cn.Open();
                FileStream fStream = File.OpenRead("C:\\Users\\pnuser\\Desktop\\PDFFiles\\VehicleInsurance.pdf");
                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();
                using (SqlCommand cmd = new SqlCommand("insert into DocumentsTable ([FileName],[Filetype],[FileContent]) values(@fileName,@fileType,@fileContent)", cn))
                {
                    cmd.Parameters.AddWithValue("@fileName", "VehicleInsurance.pdf");
                    cmd.Parameters.AddWithValue("@fileType", ".pdf");
                    cmd.Parameters.AddWithValue("@fileContent", contents);
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Pdf File Saved in Db");
                }
            }
        }
    }
}

C# Code to Retreive PDF Files from Database
using System;
using System.Data.SqlClient;

namespace CSharpConceptsDemo
{
    class PDFFilesReadFromDB
    {
        static void Main(string[] args)
        {
            string ToSaveFileTo = "C:\\Users\\pnuser\\Desktop\\PDFFiles\\OutputFiles\\VehicleInsurance.pdf";
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            string credentials = System.Configuration.ConfigurationManager.ConnectionStrings["SqlDBkey"].ToString();
            using (SqlConnection cn = new SqlConnection(credentials))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand("select [FileContent] from [DocumentsTable]  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();
                    }
                }
            }

        }
    }
}

No comments: