Tuesday, July 15, 2014

Open doc,txt or pdf files in C#

This example shows you how to open any doc,txt or pdf file which is saved in any specified location.In this example I m using a GridView which contains a template field which holds FileName.
<asp:TemplateField HeaderText="Application Name" SortExpression="ApplicationName">
        <itemtemplate>
                       <asp:LinkButton ID="lbOpenApplication" runat="server" Text='<%# Bind("ApplicationName") %>'  CommandArgument='<%# Bind("ApplicationName") %>' CommandName="ViewApplication"></asp:LinkButton>
       </itemtemplate>
    </asp:TemplateField>

In Gridview's RowCommand event we have to write code snippet given below.
protected void gvViewLeave_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ViewApplication")
        {
            string filename = e.CommandArgument.ToString();
            string path = Server.MapPath("~/PayRoll/Applications/");
            System.Diagnostics.Process.Start(path + filename);
        }
    }