Thursday, May 5, 2016

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

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 asp.net using C#, VB.net.

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


Description:

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.

Implementation:
HTML Markup:
<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="25%"
            onrowdatabound="GridView1_RowDataBound"
            onrowcommand="GridView1_RowCommand" CellPadding="4" ForeColor="#333333"
            GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
        <asp:BoundField DataField="FileName" HeaderText="File Name" >
            <ItemStyle HorizontalAlign="Justify" />
            </asp:BoundField>
        <asp:TemplateField HeaderText="View File">
                    <ItemTemplate>
                    <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>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
        </Columns>
            <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" />
        </asp:GridView>
        </ContentTemplate>
        </asp:UpdatePanel>

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;

VB.net 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)
        {
            Bindgrid();
        }
    }
    public void Bindgrid()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_File", con);
            dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (Exception ex)

        {
        }
    }

VB.net 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
            Bindgrid()
        End If
    End Sub
    Public Sub Bindgrid()
        Try
            Dim adp As New SqlDataAdapter("Select * from Tb_File", con)
            dt = New DataTable
            adp.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        Catch ex As Exception
        Finally
            dt.Dispose()
        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";
    }

VB.net 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;
            Process.Start(processinfo);
        }
    }

VB.net 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
            Process.Start(processinfo)
        End If
    End Sub

Build, run the application and test the application. 


No comments:

Post a Comment