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

← PrevNext →

Last updated: 11th October, 2023

Access to files and folders in a remote server can be limited. But, .net 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.

Once you have successfully extracted a file from the folder, it shows detail information about the file. However, in our demo we will show few other properties like the file Name, Size, Extension or Type and it's "Creation Date". Typically, it gives the user an insight of the type of files dumped in a specified folder.

extract files from folder and show in gridview

Also added in this example is how to extract and browse a list of files with a particular extension. For this purpose, we will use an Asp.Net "Listbox" control, which will have a predefined list of file types. Once, you choose a particular File type you will click a button to postback information to the server.

The Markup

Files are extracted (from folders) using classes like "DirectoryInfo() and FileInfo()" of System.IO namespace. We can then bind the list of files, f either particular type or all the files in a folder, to a GridView control.

<!DOCTYPE html>
<html>
<head>
    <title>Extract files from Folder and show in GridView</title>
    <style type="text/css">
        
        <!--add some style to gridview and other controls-->

        * {
            font-family: Calibri; 
            font-size: 18px;
        }
        div { 
            width: 750px; 
        }
        .grid { width: 100%; background-color:#FFF; border:solid 1px #525252}
        .grid td { 
            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; 
            text-align: center; 
            text-transform: capitalize;
        }
        #drop1 { 
            width: 70px; 
            padding: 3px 
        }
    </style>
</head>

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

    <div>
        <%--ListBox to show 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>

Also Read: Extract Files from Folder and Display using a Repeater Control in Asp.Net

Code Behind (C#)
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_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";
        }
    }
}
Vb.Net
Option Explicit On
Imports System.IO

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub btShowFiles_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) 
        Handles btShowFiles.ServerClick
        
        ViewState("FileType") = drop1.SelectedValue     ' GET THE FILE TYPE.
        GetFilesFromFolder()
    End Sub

    ' GRIDVIEW PAGING.
    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, 
            ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) 
                Handles GridView1.PageIndexChanging
            
        GridView1.PageIndex = e.NewPageIndex
        GetFilesFromFolder()
    End Sub

    Private Sub GetFilesFromFolder()
        ' GET A LIST OF FILES FROM A SPECIFILED FOLDER.
        Dim objDir As New DirectoryInfo(Server.MapPath("my_folder\"))   

        Dim listfiles As FileInfo() = objDir.GetFiles("*." & IIf(ViewState("FileType") <> "All", 
            ViewState("FileType"), "*"))

        If listfiles.Length > 0 Then
            'BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
            GridView1.DataSource = listfiles : 
            GridView1.DataBind()
            lblMsg.Text = listfiles.Length & " files found"
        Else
            GridView1.Visible = False : lblMsg.Text = "No files found"
        End If
    End Sub
End Class

We hope you will find this example useful. Happy coding. 🙂

← PreviousNext →