PDF,Excel,Word File Reader In C#
Bookmark
 

Rating: 4.50/5
1 2 3 4 5
2 people have rated this article

 
Posted On: Jun 18 2008
Views: 2589
BookMarked: 2
Downloads: 217
 
 
In asp.net, there is no built-in control that lets you open a file. You might need an additional logic to open the files. File Reader Control is a custom control which lets you to open .pdf, .doc, .jp, .bmp, .xls, .sql, .txt, .html etc files. It just a traditional ASP.NET button control with custom functionality to open any type of files without writing any extra logic.

File Reader Control Walkthrough
  • The File Reader Control inherits LinkButton or Button or ImageButton. 
  • It has attribute to hold the file path.
  • It contains HttpHandler which provides the logic for opening files depending on their types.
  • File Reader Control  uses a javascript function to create form in page. Also it adds hiddent input tag to the newly created form. This hidden input tag serves as medium between aspx page and http handler. When the request is generated from the page, the JavaScript function creates the form and submits.
  • This action invokes the Httphandler. It reads the newly created form's context values. After getting the full file path,it passes it to the custom logic.
  •  Control opens the file without a post back on aspx form.

Code Snippets

File Path Attribute code given below
private string _filePath;
[Category("Appearance")]
public string FilePath
{
get { return _filePath; }
set
{
_filePath = value;
_filePath = _filePath.Contains("\\\\") ? _filePath : _filePath.Replace("\\", "\\\\");
this.Attributes["onclick"] = String.Format("javascript:ShowMyFile('{0}');return false;", _filePath);
}
}

You may notice that above code block substitutes \\\\ for \\. The reason for this substitution is file path is used in two c# code blocks and one JavaScript function.If you don't use this substition, you may end up getting file path without any back slash.


Using following code, register the JavaScript function in OnInit() method of your Custom Control File.
 Page.ClientScript.RegisterClientScriptBlock(GetType(), "FileReaderControlScript", JavaScriptFunction, true);

function ShowMyFile(FilePath)
{
var FileReaderIFrame;
var FileReaderForm;
var FilePathInput;
var IFrameContent;
var FilePathBox;
//Check whether alraedy IFrame is created?
if(!document.getElementById('FileReaderIFrame'))
{
//Create a IFrame
FileReaderIFrame=document.createElement('iframe');
//Define IFrame name and id
FileReaderIFrame.name=FileReaderIFrame.id='FileReaderIFrame';
//Define IFrame styles FileReaderIFrame.style.height=FileReaderIFrame.style.width=FileReaderIFrame.style.border='0px';
//Add the frame to the page
document.body.appendChild( FileReaderIFrame);
}
//Define what needs to be in the IFrame
IFrameContent = '<form id=FileReaderHandlerForm method=post enctype=application/data action=FileReaderHandler.ashx>';
IFrameContent += '<input id="FilePath" name="FilePath" type="hidden" />';
IFrameContent += '</form>';
//open the IFrame
FileReaderIFrame= window.frames['FileReaderIFrame'];
FileReaderIFrame.document.open();
//Add form and Hidden input tag
FileReaderIFrame.document.write(IFrameContent);
//Close the Iframe
FileReaderIFrame.document.close();
FilePathBox=FileReaderIFrame.document.getElementById('FilePath');
if(FilePathBox) { FilePathBox.value=FilePath; } FileReaderForm=FileReaderIFrame.document.getElementById('FileReaderHandlerForm');
if(FileReaderForm) { FileReaderForm.submit(); } return false; }
File Reader Handler code given below:
<%@ class="FileReaderHandler" language="C#" webhandler="" %> using System;
using System.Web;
using System.IO;
using System.Configuration;
public class FileReaderHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
String strFilePath = HttpUtility.UrlDecode(context.Request.Params["FilePath"]);
if(!String.IsNullOrEmpty(strFilePath.Trim()))
{
FileInfo fi = new FileInfo(strFilePath);
if (fi.Exists)
{
System.IO.FileStream fs= new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
context.Response.Clear();
if(String.Equals(fi.Extension,".pdf",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "application/octet-stream";
else if(String.Equals(fi.Extension,".doc",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "application/vnd.msword";
else if(String.Equals(fi.Extension,".xls",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = " application/vnd.xls";
else if(String.Equals(fi.Extension,".jpg",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "image/jpg";
else if(String.Equals(fi.Extension,".jpeg",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "image/jpeg";
else if(String.Equals(fi.Extension,".gif",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "image/gif";
else if(String.Equals(fi.Extension,".png",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "image/png";
else if(String.Equals(fi.Extension,".bmp",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "image/bmp";
else if(String.Equals(fi.Extension,".txt",StringComparison.OrdinalIgnoreCase)) context.Response.ContentType = "text/plain";
else context.Response.ContentType = "text/HTML";
context.Response.AddHeader("Content-Length", buffer.Length.ToString()); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name); context.Response.BinaryWrite(buffer);
}
}
} catch(Exception ex) { } }
public bool IsReusable
{ get { return false; } } }

File Reader Control Usage
  • Register in the page.

<%@ Register TagPrefix="cc1" Namespace="CustomControls" %>

  • Set File Path Through Programmatically

<cc1:filereadercontrol id="FileReaderControl1" runat="server">Open My File</cc1:filereadercontrol>

FileReaderControl1.FilePath = "c:\\1.pdf";

  •  Set File Path Through Property Window

<cc1:filereadercontrol id="FileReaderControl2" runat="server" filepath="c:\\1.pdf">Open My File</cc1:filereadercontrol>


You can use this control like a button. It can open pdf, doc, avi, jpg, jpeg, png, sql, xls etc.


Rate This Article

Please Sign In In to post messages.