Introduction
This article shows how to fetch the document files, like PDF, Word and Excel documents, from a database.
For an explanation of that in this article, I will use the following procedure:
- Create a table in the database to store the document files and some other relevant data by which I can fetch the file from the table and store some data into the table.
- Create a website with a generic handler (.ashx) with some code, that will fetch the specific file from the database.
- Create a page, that shows all the files and call the generic handler (.ashx) for the specific file.
The following are the details of the preceding procedure.
Step 1
1. Create a table named "Documents" that will store:
- Identity column for Serial number
- Name of the file
- Display File name that you want to show
- Extension of file
- Content Type of file
- File in binary format
- Size of file
- Date of file insertion
- create table Documents
- (
- SNo int identity,
- Name_File varchar(100),
- DisplayName varchar(50),
- Extension varchar(10),
- ContentType varchar(200),
- FileData varbinary(max),
- FileSize bigint,
- UploadDate datetime
- )

Note
To understand how to save the document files in the database, read my previous article "How to Save PDF, Word and Excel Files Into The DataBase".
Step 2
- Create a new empty Website named "FilesToBinary".

- Add a new Generic Handler named "DocHandler.ashx".

Which will look like:
- Add a web form named "GetFiles.aspx".

- Add some code in the ".cs" file of the GetFiles page for fetching all the files from the database.
- protected void Page_Load(object sender, EventArgs e)
- {
- //Fetch the Data from Database
- string sConn = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ToString();
- SqlConnection objConn = new SqlConnection(sConn);
- objConn.Open();
- string sTSQL = "select * from Documents";
- SqlCommand objCmd = new SqlCommand(sTSQL, objConn);
- objCmd.CommandType = CommandType.Text;
- SqlDataAdapter ada = new SqlDataAdapter(objCmd);
- DataTable dt = new DataTable();
- ada.Fill(dt);
- objConn.Close();
- objCmd.Dispose();
- //Bind the Data into the html anchor tag which will call the handler with ID
- if (dt.Rows.Count > 0)
- {
- string tbl = "";
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- tbl += @"<li>
- <a target='_blank' href='DocHandler.ashx?ID=" + dt.Rows[i]["SNo"].ToString();
- tbl += @"' title='";
- tbl += @"' >" + dt.Rows[i]["DisplayName"].ToString();
- tbl += @"</a>
- </li>";
- }
- Response.Write(tbl);
- }
- }
Get the file from the database via a handler as in the following:
1. Delete or comment the 2 default generated lines, that are mentioned below. just because of irrelevancy.
- context.Response.ContentType = "text/plain";
- context.Response.Write("Hello World");
- string id = context.Request.QueryString["ID"].ToString();
- string sConn = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ToString();
- SqlConnection objConn = new SqlConnection(sConn);
- objConn.Open();
- string sTSQL = "select Name_File,Extension,ContentType,FileData,FileSize from Documents where SNo=@ID";
- SqlCommand objCmd = new SqlCommand(sTSQL, objConn);
- objCmd.CommandType = CommandType.Text;
- objCmd.Parameters.AddWithValue("@ID", id);
- SqlDataAdapter ada = new SqlDataAdapter(objCmd);
- DataTable file = new DataTable();
- ada.Fill(file);
- objConn.Close();
- objCmd.Dispose();
- if (file.Rows.Count > 0)
- {
DataRow row = file.Rows[0]; - string name = (string)row["Name_File"];
- string contentType = (string)row["ContentType"];
- Byte[] data = (Byte[])row["FileData"];
- int FileSize = Convert.ToInt32(row["FileSize"].ToString());
- // Send the file to the browser
- context.Response.AddHeader("Content-type", contentType);
context.Response.AddHeader("Content- Disposition", "attachment; filename=" + name); - context.Response.OutputStream.Write(data, 0, FileSize);
- context.Response.Flush();
- context.Response.End();
- }
Run the page that will be like:

Click on the file that you want to download.
- DocFile

- PDF

- Excel

Result
Now you have all 3 files stored in the database in binary format.

Jitendra KumarPosted Jan 8, 2018, 5:39 AM
Hi,sir, i have some error in my link button code , seek your help. in link button . onClick="Download" CommandArgument='<%=_objdt.Rows[i]["Visitor_ID"].ToString()%>' but CommandArgument does not retrieve any value
Aasim InamdarPosted Sep 18, 2015, 11:50 PM
Hi rahul i m working for a digital library web application where student can should only view the book and not able to download or copy the text... so plz help me out in this thnx
Rahul BansalPosted Mar 28, 2015, 12:35 PM
DocHandler.ashx will fire when you will click on the hyperlink of file like DocFile, pdf and excel.If you want to display the name like 'Test.xlsx' or 'Test.xls' then try the name_file filed instead of displayname in DocHandler.ashx
Taraka PrabhuPosted Mar 28, 2015, 11:43 AM
Really cool article, but i got few doubts, when will the DocHandler.ashx will be fired, i kept breakpoint in DocHandler.ashx, but it never come there, and the list in GetFiles.aspx always shows "ExcelFile" instead of "Test.xlsx", please help me out.....
hothorasman panjaitanPosted Nov 25, 2014, 1:00 PM
hi Rahul Bansal I follow the example your article, how when I click viewdetails, it will show all the records along with the files, to the details page-view.aspx
Ramesh MaruthiPosted Jul 18, 2014, 11:28 AM
Good article :)