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" %> <html> <head> <meta name="generator" Content="ASP Express 5.1"> <title>Untitled</title> <script language="C#" Runat="server"> // declare the page level variable for the path String FilePath; protected void Page_Load(object sender, EventArgs e) { FilePath=Server.MapPath("~/Files"); 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(); dt.Columns.Add("FileName",typeof(System.String)); dt.Columns.Add("Size",typeof(System.String)); 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=dt.NewRow(); dr[0] = fi.Name.ToString(); dr[1] = fi.Length.ToString("N0"); //'N0'formats the number with commas dt.Rows.Add(dr); } // Bind DataTable to GridView - voila! grdFiles.DataSource = dt; grdFiles.DataBind(); } </script> </head> <body> <form id="form1" Runat="server"> <div style="text-align:center"> <asp:Label ID="lblHeader" runat="server"></asp:Label> <asp:GridView ID="grdFiles" runat="server"> </asp:GridView> </div> </form> </body> </html>