Getting a Directory's File List

Sometimes, it becomes necessary to actually list the files in a particular directory. To do this, we import the System.IO namespace. This code sample shows two different ways to display the directory. One way uses a Literal control to merely list them on the page, and the other uses a DropDownList control.

Additionally, we show ways to navigate to the files which are listed with each type of display. The DropDownList uses a simple redirector script, while the Literal control surrounds the filename with an HTML anchor tag.

To make this work on your system, just copy the code to your new file and change the path info to match that of your system.

<%@ Import Namespace="System.IO" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim strFilePath as String
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strEntries() As String
	Dim f, sFiles As String
	strFilePath = Server.MapPath("/files/")
	strEntries = Directory.GetFiles(strFilePath)

	For Each f In strEntries
		Dim Filename as String=path.GetFilename(f)
		if not Page.IsPostBack then
			ddl.items.add(Filename)
		end if
		strFilePath=strFilePath.Replace("\", "/")
		strFilePath=strFilePath.Replace("c:/Inetpub/wwwroot", "")

		sFiles=sFiles & "<a href=" & chr(34) & strFilePath & Filename & chr(34) & ">" & Filename & "</a><br>"
		lt.text=sFiles
	Next
End Sub

Sub doit(Source as Object, E as EventArgs)
	Dim sRedir as string
	strFilePath = Server.MapPath("/files/")

	sRedir = strFilePath & ddl.selectedItem.text
	sRedir=sRedir.Replace("\", "/")
	sRedir=sRedir.Replace("c:/Inetpub/wwwroot", "")
	response.Redirect(sRedir)
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<asp:DropDownList id="ddl" runat="server" />
<asp:Button id="button1" Text="Do It" onclick="doit" runat="server" /><br>
<asp:Literal ID="lt" runat="server"></asp:literal>
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>

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>