Listing Folders in a Directory using asp.net and C

2019-01-19 22:51发布

.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.

4条回答
祖国的老花朵
2楼-- · 2019-01-19 23:26

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

查看更多
Luminary・发光体
3楼-- · 2019-01-19 23:31

Response.Write in a static codebehind method: DIRTY! In addition you did't control the position where you write. This a little bit cleaner...

// YourPage.aspx
<%@ Import Namespace="System.IO" %>
<html>
<body>
    <ul>
        <% foreach(var file in Directory.GetFiles("C:\\Temp", "*.*", SearchOption.AllDirectories)) { %>
        <li><%= file %></li>       
        <% } %>     
    </ul>
</body>
</html>
查看更多
4楼-- · 2019-01-19 23:42

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>
查看更多
叛逆
5楼-- · 2019-01-19 23:43

Console.WriteLine will write to the console, not the web page contents you are returning. You need to add a container element to your ASPX page, probably a grid view or repeater, then add assign the file list from the code behind file (to the HTML element you added, use the runat='server' tag and assign it an ID, then reference it by ID name in the code).

查看更多
登录 后发表回答