List the files in a directory using ASP.Net and C#

Being able to list the files in a directory is a pretty handy thing to do. Here is an example of how to do this in in ASP.Net using C#.

<script runat="server">
 string output = "";  
 protected void Page_Load(object sender, System.EventArgs e)
 {
   string path = Server.MapPath(".");
   DirectoryInfo di = new DirectoryInfo(path);
   FileInfo[] rgFiles = di.GetFiles("*.*");
   foreach (FileInfo fi in rgFiles)
   {
     output = output + "<p>" + fi.Name + "</p>";
   }
 }
 ...
</script>
<body>
 ...
 <% Response.Write(output); %>
 ...
</body>

No comments: