Tuesday, 17 March 2015

Extract Files from Folder and Bind with Asp.Net GridView – C#

Access to files and folders in a remote server can be limited, but .Net has provided us with a variety of classes in its “System.IO” namespace, exclusively for safely manipulating and viewing files like ‘Word’, ‘Excel’, ‘PDF’, ‘JPG’ etc. Once files are extracted from the folder, we can bind all the files to an Asp.Net GridView control to allow users to view it on a web page.


ASPX Code:
<!DOCTYPE html>

<html>
<head>
    <title>Display | Bind Files from Folder to GridView</title>

    <style type="text/css">
        div
        {
            font:11px Verdana;
            width:750px;
        }

        .grid
        {
            width:100%;
            font:inherit;
            background-color:#FFF;
            border:solid 1px #525252;
        }
       
        .grid td
        {
            font:inherit;
            padding:2px;
            border:solid 1px #C1C1C1;
            color:#333;
            text-align:center;
            text-transform:uppercase;
        }
       
        .grid th {
            padding:3px;
            color:#FFF;
            background:#424242 url(grd.png) repeat-x top;
            border-left:solid 1px #525252;
            font:inherit;
            text-align:center;
            text-transform:uppercase;
        }
       
        #drop1
        {
            width:70px;
            padding:3px;
        }

    </style>
</head>

<body>
    <form id="form1" runat="server">

    <div>

        <%--LISTBOX SHOWING A LIST OF FILE TYPES.--%>
       
        <p>
            <asp:ListBox id="drop1" rows="3" runat="server">
                    <asp:ListItem selected="true">All</asp:ListItem>
                    <asp:ListItem>pdf</asp:ListItem>
                    <asp:ListItem>jpg</asp:ListItem>
                    <asp:ListItem>png</asp:ListItem>
                    <asp:ListItem>txt</asp:ListItem>
                    <asp:ListItem>doclt/asp:ListItem>
                </asp:ListBox>

                <input type="button" id="btShowFiles" onserverclick="btShowFiles_Click"
                    value="Show Files" runat="server" />
        </p>
      
        <%--ADD A GRIDVIEW WITH FEW COLUMNS--%>
        <asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true"
            AllowPaging="true" PageSize="5" AutoGenerateColumns="false"
            OnPageIndexChanging="GridView1_PageIndexChanging" runat="server">
               
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate><asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Length">
                    <ItemTemplate><asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="File Extention">
                    <ItemTemplate><asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Creation Date & Time">
                    <ItemTemplate><asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>'>
                        </asp:Label></ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
       
        <%--A LABEL SHOWING NUMBER OF FILES FOUND IN THE FOLDER.--%>
        <p><asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>

    </div>
    </form>

</body>
</html>

C# Code:
using System;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void btShowFiles_Click(object sender, EventArgs e)
    {
        ViewState["FileType"] = drop1.SelectedValue;     // GET THE FILE TYPE.
        GetFilesFromFolder();
    }

    // GRIDVIEW PAGING.
    protected void GridView1_PageIndexChanging(object sender,
        System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GetFilesFromFolder();
    }

    private void GetFilesFromFolder()
    {
        // GET A LIST OF FILES FROM A SPECIFILED FOLDER.
        DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("my_demo_folder\\"));   
       
        FileInfo[] listfiles = objDir.GetFiles("*." + ((string)ViewState["FileType"] != "All" ?
            ViewState["FileType"] : "*"));

        if (listfiles.Length > 0)
        {
            // BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
            GridView1.Visible = true;
            GridView1.DataSource = listfiles;
            GridView1.DataBind();

            lblMsg.Text = listfiles.Length + " files found";   
        }
        else {
            GridView1.Visible = false ;
            lblMsg.Text = "No files found";
        }
    }
}