Displaying the Files from a Directory using a DataGrid ASP.Net

In the code snippet, we show you how you can get the files from a folder and show in a grid

Call this Namespace alobg with default namespaces in .cs page.
using System.IO;

 private void GetFilesFromFolder()
    {

        String FilePath = Server.MapPath("../uploads/photos/");
        //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("FileSize", typeof(System.String));
        DataRow dr = null;
        DirectoryInfo dir = new DirectoryInfo(FilePath);
    
        // adding file to a datatable one by one in new row, along with the  filesize to each file
        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);
        }
        datagridFiles.DataSource = dt;
        datagridFiles.DataBind();
     
    }

In ShowFiles.aspx page, add the datagrid, gridview etc

<form id="form1" Runat="server">
    <div style="text-align:center">
        asp:DataGrid ID="datagridFiles" runat="server"></asp:DataGrid >
   </div>
</form>

Related Alrticles

Add Your Business in Free Listing


FREE!!! Registration