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

自作多情 提交于 2019-11-28 12:36:43
benwasd

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>

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

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

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!