A simple asp.net application for listing files and folders within a folder

We tease each other calling “Google Programmers” occasionally as we just cut and paste code from forums/websites and meet new business requirements and deadlines.

We started revamping our intranet site recently and was frantically looking at a prospective of converting few .asp driven details using .net application(s)

Our primary requirement was to list the content of a folder, along with subdirectories and files (mostly .pdf and .doc/.docx/.xls/.xlsx)

After loads of googling we came across two potential solutions and they were

http://www.4guysfromrolla.com/articles/090110-1.aspx

http://www.encodedna.com/2013/08/extract-display-files-from-folder-and-bind-with-gridview.htm

The first solution was “too” professional approach for guys like us, who hardly have anything more than few hours of experiences with .net programming

The second solution looked more appropriate as we were looking at something which could be easily altered and adopted to our particular requirement.

Hence we copied the scripts available with the link and started altering them, and with our “extreme” level of exposure to the technology, almost after 72 hours we were able to shape up something which fits into our requirements, somehow and we are sharing the same with you.

We know, it could be done much easier or in a simpler manner, well that part we are leaving for the seasoned .net developers.

First create a .aspx file with name “Default” (eg:Default.aspx) and copy the following code inside the file (Notepad++)

[sourcecode language=”html” padlinenumbers=”true”]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Display | Bind Files from Folder to GridView</title>
<style type="text/css">
div { font:11px Verdana; width:750px }
.grid { width:100%; font:inherit; background-color:#FFF; border:solid 1px #525252}
.grid td { font:inherit; padding:2px; border:solid 1px #C1C1C1; color:#333; text-align:left;
text-transform: capitalize}
.grid th { padding:3px; color:#FFF; background:#424242 url(grd.png) repeat-x top;
border-left:solid 1px #525252; font:inherit; text-align:center; text-transform:uppercase}
#drop1 { width:70px; padding:3px }
</style>
</head>
<body>
<%– <%
Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
%>–%>
<form id="form1" runat="server">
<div>
<%–LISTBOX SHOWING 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="GridView2" CssClass="grid" GridLines="None" ShowFooter="true"
AllowPaging="true" PageSize="5" AutoGenerateColumns="false"
runat="server">

<Columns>

<asp:TemplateField HeaderText="Folder(s)">
<ItemTemplate>
<asp:HyperLink runat="server" ID="HyperLink1" Text='<%# Eval("Name") %>’ NavigateUrl='<%# HttpContext.Current.Request.Url.AbsoluteUri +"/"+ Eval("Name") %>’ />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true"
AllowPaging="true" PageSize="20" AutoGenerateColumns="false"
OnPageIndexChanging="GridView1_PageIndexChanging" runat="server">

<Columns>

<asp:TemplateField HeaderText="Name">

<ItemTemplate>
<%–<asp:Label ID="lblName" runat="server" Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("Name").ToString()) %>’></asp:Label>–%>
<asp:HyperLink runat="server" ID="HyperLink2" Text='<%# System.IO.Path.GetFileNameWithoutExtension(Eval("Name").ToString()) %>’ NavigateUrl='<%#
Request.QueryString["p"] +"/"+ Eval("Name") %>’ />
</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>
[/sourcecode]

Now create another file “Default.aspx.cs” and copy the below code inside the file

[sourcecode language=”csharp”]
using System;
using System.IO;
using System.Globalization;

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();
}

protected void GetFilesFromFolder()
{
String pathname = Request.QueryString["p"];

//String pathname;

// pathname = Request.QueryString["p"];

//response.redirect("a.aspx?ids=1&val=100",true)

//and in the second page that is a.aspx

//a=Request.QueryString("ids")

//b= Request.QueryString("val")

// GET A LIST OF FILES FROM A SPECIFILED FOLDER.

DirectoryInfo objDir = new DirectoryInfo(Server.MapPath(pathname));

//(@"D:\Dell Drivers");
//(Server.MapPath("listfiles\\"));

FileInfo[] listfiles = objDir.GetFiles("*");

DirectoryInfo[] listDirs = objDir.GetDirectories(".");

if (listDirs.Length > 0)
{
GridView2.Visible = true;
GridView2.DataSource = listDirs;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
}

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";
}
}
protected void Page_Load(object sender, EventArgs e)
{
GetFilesFromFolder();
}
}
[/sourcecode]

Now move both the files to your web application folder. We were using the default “C:\inetpub\wwwroot” for the testing, hence moved the files to there.

Now you can start calling the application like following

http://localhost/Default.aspx?p=memos

Where memos is an actually folder available within “C:\inetpub\wwwroot” path

If you have folders within the “memos” folder, the application will present you view like following

image

Based on whether you have subfolders within the “memos” folder the application will either display or hide the Folder(s) grid, the same applies to Files grid as well

The best part is, this application can drill down into any level of nested folders and populate folder and file lists as URLs.

We thank A2S from forums.asp.net for helping us to strip out the extensions from filenames. Please refer to the below link for more details.

http://forums.asp.net/t/1958264.aspx?Stripping+the+extension+from+file+name+derived+using+Eval+Name+

Enjoy guys!

After all it is another wonderful Christmas time

regards,

for Windows7bugs

rajesh