Extract Files from Folder and Bind with ASP.NET GridView using 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

This example also demonstrates how to extract and browse a list of files based on a specific file extension. To accomplish this, we use an ASP.NET ListBox control that contains a predefined list of file types. After selecting a file type from the list, the user can click a button to submit the selection to the server and retrieve the corresponding files.

The Markup

Files are retrieved from directories using the DirectoryInfo and FileInfo classes provided by the System.IO namespace. The resulting file list either filtered by a specific file type or including all files within a folder, can then be bound to a GridView control for display.

<!DOCTYPE html>
<html>
<head>
    <title>Extract files from Folder and show in GridView</title>
</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>
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

← PreviousNext →