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

5

5

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

Tribrach answered 18/5, 2011 at 15:29 Comment(0)
F
15

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>
Falsify answered 18/5, 2011 at 16:17 Comment(4)
Im trying to do something similar but i dont want to use a static path. Is there a way to get the application path? for example "~/Uploads/" and Uploads is a folder inside of my web project. I dont want to have this: "C://Visual Studio 2013/ projects/my project" etcReproachless
@Ra3IDeN yes, use HttpContext.Current.Server.MapPath(StringPathInSolution) , however as the path to your project is static and thus known you could remove it from the string?Adai
it does not fetch files in my caseTetraploid
Correct! You are Pro!Stoplight
A
1

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

Ariosto answered 18/5, 2011 at 15:36 Comment(9)
I'm getting this error : An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Response.get'Tribrach
@ILLUMINATI7590: Oh, remove static from private static void GetFilesFromDirectory(string DirPath). You don't need it in this case.Ariosto
Thank you It removed the error .But my web page is still showing nothing.Tribrach
@ILLUMINATI7590: Are you sure no errors are being thrown? Did you replace both instances of Console.WriteLine()?Ariosto
yes I replaced all instances and I still get nothing.Getting the page same as earlier.Tribrach
Try putting a break-point (assuming you're running from an IDE) in the GetFilesFromDirectory method and see if you can step into it (F11 while execution is paused at the break-point).Ariosto
In my oppinion Response.Write doesn't work at Page_Load/Pre_Init and such events. The Response will cleard bevor rendering aspx.Falsify
I couldn't understand it.But can you help me in just displaying folders(not subfolders) in the way benjamin told.Tribrach
@ILLUMINATI7590: If this didn't work for you, and Benjamin's did, you should award the answer to him, not to me. I'm sure he'd be able to help you with his code. :)Ariosto
T
1

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

Talmud answered 18/5, 2011 at 15:38 Comment(0)
F
1

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>
Falsify answered 18/5, 2011 at 15:46 Comment(3)
You have your <li> and <ul> mixed up. Also, I do agree with you but the user seems to just be doing something basic right now (the page is blank and there's nothing else in the code-behind) so I didn't really see the point of getting into perfecting the display. Also, I didn't even notice that the method was static`, good eyes. :)Ariosto
Thank you very much.I'm very new to coding.Tribrach
Please tell me this.I just want to display folders in a directory(not subfolders).In your code replacing Files with Directories giving every folder in it.Tribrach
A
0

You can use Directory class

  • The first parameter is the path it can be relative or absolute
  • The second parameter for matching against the names of subdirectories in path. This parameter can contain a combination of valid literal and wildcard characters, but it doesn't support regular expressions.

/

//using System.IO; 
private void GetDirectories()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("direction",typeof(string));
    try
    {
        string[] dirs = Directory.GetDirectories(@"yourpath", "*", SearchOption.AllDirectories);
        foreach (string dir in dirs)
        {
            dt.Rows.Add(dir);
        }
        if (dirs.Length <= 0)
        {
             lbl.text="your message"

        }

       rpt.DataSource = dt; //your repeater 
       rpt.DataBind(); //your repeater 
    }
    catch (Exception e)
    {
       lbl.text="your message"//print message assign it to label
    }
}

In the aspx page

   <asp:Label runat="server" ID="lbl"></asp:Label>
    <asp:Repeater ID="rpt" runat="server" ClientIDMode="AutoID">
        <ItemTemplate>
            <tr>
                <td><%#Eval("direction")%></td>

            </tr>
        </ItemTemplate>
    </asp:Repeater>
Aaren answered 29/10, 2019 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.