Filling a Grid with Files in a Folder – C#

This code sample shows, in C#, how to get all the files within a specific folder, and list them all, including the file size, in a Gridview control.

To access the FileSystem, you’ll need to import the System.IO namespace, and to use a DataTable, you must import the System.Data namespace:
using System.IO;
using System.Data;

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.IO" %>
		<meta name="generator" Content="ASP Express 5.1">
<script language="C#" Runat="server">
// declare the page level variable for the path
		String FilePath;
        protected void Page_Load(object sender, EventArgs e)
            GetFiles();  //call the GetFiles method
            lblHeader.Text = "Files in " + FilePath;
        private void GetFiles()
            //Create the DataTable, with columns in which to add the file list
            DataTable dt=new DataTable();
            DataRow dr=null;
            DirectoryInfo dir=new DirectoryInfo(FilePath);

            // Iterate through the datatable,
			// adding file to a new row, along with the  filesize to each row
            foreach (FileInfo fi in dir.GetFiles())
                dr[0] =  fi.Name.ToString();
                dr[1] = fi.Length.ToString("N0");  //'N0'formats the number with commas
            // Bind DataTable to GridView - voila!
            grdFiles.DataSource = dt;

		<form id="form1" Runat="server">
	    <div style="text-align:center">
	        <asp:Label ID="lblHeader" runat="server"></asp:Label>
	        <asp:GridView ID="grdFiles" runat="server">

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>