Open (view) all type of files with associate program in using C#,

In this article I am going to explain how to open (view) all type of files (images, word document, excel, PDF etc.) with associate program in using C#,

Open (view) all type of files with associate program in using C#,


I am displaying the filename with their path in Gridview.I want to open/view file on click. To implement this requirement we can use the Procees class. It provides access to local and remote processes and enables you to start and stop local system processes.

HTML Markup:
<asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="25%"
            onrowcommand="GridView1_RowCommand" CellPadding="4" ForeColor="#333333"
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <asp:BoundField DataField="FileName" HeaderText="File Name" >
            <ItemStyle HorizontalAlign="Justify" />
        <asp:TemplateField HeaderText="View File">
                    <img id="fileImage" runat="server"/>
                        <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Filepath") %>' />
                        <asp:LinkButton ID="lnkFile" runat="server" CommandArgument='<%# Eval("Filepath") %>' CommandName="ViewFile" Text='<%# Eval("FileName") %>' ></asp:LinkButton>
                    <ItemStyle HorizontalAlign="Left" />
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

Import namespace
C# Code:
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Diagnostics; Code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO
Imports System.Web.UI.HtmlControls
Imports System.Diagnostics

Bind the gridview
Create a method to bind the gridview and call it on page load.
C# Code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
    public void Bindgrid()
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_File", con);
            dt = new DataTable();
            GridView1.DataSource = dt;
        catch (Exception ex)

    } Code:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Dim dt As New DataTable
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        End If
    End Sub
    Public Sub Bindgrid()
            Dim adp As New SqlDataAdapter("Select * from Tb_File", con)
            dt = New DataTable
            GridView1.DataSource = dt
        Catch ex As Exception
        End Try
    End Sub

Get file icon and show
Write the below code on RowDataBound of Gridview.
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            LinkButton linkbtn = (LinkButton)e.Row.FindControl("lnkFile");
            HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");
            if (!String.IsNullOrEmpty(linkbtn.Text))
                HtmlImage image = (HtmlImage)e.Row.FindControl("fileImage");
                image.Attributes.Add("src", GetIconForFile(hf.Value));
    private string GetIconForFile(string fileText)
        string extension = Path.GetExtension(fileText);
        extension = extension.Trim('.').ToLower();
        return "~/fileicons/" + extension + ".png";
    } Code:
  Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim linkbtn As LinkButton = DirectCast(e.Row.FindControl("lnkFile"), LinkButton)
            Dim hf As HiddenField = DirectCast(e.Row.FindControl("HiddenField1"), HiddenField)
            If Not [String].IsNullOrEmpty(linkbtn.Text) Then
                Dim image As HtmlImage = DirectCast(e.Row.FindControl("fileImage"), HtmlImage)
                image.Attributes.Add("src", GetIconForFile(hf.Value))
            End If
        End If
    End Sub
    Private Function GetIconForFile(fileText As String) As String
        Dim extension As String = Path.GetExtension(fileText)
        extension = extension.Trim("."c).ToLower()
        Return (Convert.ToString("~/fileicons/") & extension) + ".png"
    End Function

Open File with appropriate program
Write the below given code on Rowcommand event of GRidview.

C# Code:
  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        if (e.CommandName == "ViewFile")
            string fileName = Server.MapPath(e.CommandArgument.ToString());          
            ProcessStartInfo processinfo = new ProcessStartInfo();
            processinfo.FileName = fileName;
            processinfo.UseShellExecute = true;
            processinfo.WindowStyle = ProcessWindowStyle.Maximized;
    } Code:
Protected Sub GridView1_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        If e.CommandName = "ViewFile" Then
            Dim fileName As String = Server.MapPath(e.CommandArgument.ToString())
            Dim processinfo As New ProcessStartInfo()
            processinfo.FileName = fileName
            processinfo.UseShellExecute = True
            processinfo.WindowStyle = ProcessWindowStyle.Maximized
        End If
    End Sub

Build, run the application and test the application. 

Post a Comment



Contact Form


Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget