Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing Folders in a Directory using asp.net and C#

.aspx file:

<%@ Import Namespace="System.IO" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Explorer</title>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>

.CS file:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.IO;

public partial class view2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    string path = "~/";
    GetFilesFromDirectory(path);
}

private static void GetFilesFromDirectory(string DirPath)
{
         try
         {
             DirectoryInfo Dir = new DirectoryInfo(DirPath);
             FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
             foreach (FileInfo FI in FileList)
             {
                 Console.WriteLine(FI.FullName);
             }
         }
         catch (Exception ex)
         {
                Console.WriteLine(ex.Message);
         }
}

I want to list the folders in a particular directory but it continuously showing blank page.Can anybody tell what's the problem in the code.

like image 595
Naresh Avatar asked May 18 '11 15:05

Naresh


People also ask

What are folders or directories in C#?

A directory, also called a folder, is a location for storing files on your computer. In addition to files, a directory also stores other directories or shortcuts. In C# we can use Directory or DirectoryInfo to work with directories. Directory is a static class that provides static methods for working with directories.


2 Answers

Display directories and files on a blank page

// YourPage.aspx
<%@ Import Namespace="System.IO" %>
<html>
<body>
    <% foreach (var dir in new DirectoryInfo("E:\\TEMP").GetDirectories()) { %>
        Directory: <%= dir.Name %><br />

        <% foreach (var file in dir.GetFiles()) { %>
            <%= file.Name %><br />
        <% } %>
        <br />
    <% } %>
</body>
</html>
like image 106
benwasd Avatar answered Oct 19 '22 17:10

benwasd


Don't use Console.WriteLine() use Response.Write(). You're trying to write to the console in a web application.

like image 30
Richard Marskell - Drackir Avatar answered Oct 19 '22 18:10

Richard Marskell - Drackir