Filling a Grid with Files in a Folder

Posted by David Wier on 02/4/10 | Code Samples

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:
usingSystem.IO;
usingSystem.Data;

All you need in the main .ASPX page is a label (called lblHeader) and a Gridview (called grdFiles):

<divstyle="text-align:center">
<asp:Label ID="lblHeader" runat="server"></asp:Label>
<asp:GridView ID="grdFiles" runat="server”>
</asp:GridView>
</div>

Then, in the Code behind, here’s your code:

        StringFilePath; // declare the page level variable for the path 
        
protected voidPage_Load(objectsender, EventArgse) 
        

            
FilePath=Server.MapPath("~/Files");
            
GetFiles();  //call the GetFiles method 
            
lblHeader.Text = "Files in "+ FilePath;
        } 
        
private voidGetFiles()
        

            
//Create the DataTable, with columns in which to add the file list 
            
DataTabledt=new DataTable(); 
            
dt.Columns.Add("FileName",typeof(System.String)); 
            
dt.Columns.Add("Size",typeof(System.String)); 
            
DataRowdr=null;
            
DirectoryInfodir=new DirectoryInfo(FilePath);

            // Iterate through the datatable, 
            
// adding file to a new row, along with the  filesize to each row 
            
foreach(FileInfofi indir.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();
        
}

 














































0 Comments

COMMENTS

Name:
URL:
Comment:

Comments are disabled for this article.