Search code examples
c#.netasp.netfile-browser

ASP.NET file browser path translation


I'm working on an asp.net file browser that recursively goes through folder and lists their files and subfolders. However I also want to make the files possible to download/view and it’s there I seem to have a problem. I can’t get the address translation correct. I have the following configuration and code.

Edit:

The problem is that the links that are created

Response.Write(space + "<a href=" + "Upload/" + d.Name + ">" + d.FullName + "</a><br/>");

Do not link to the file correctly. Also there is a bonus problem that I need to resolve: some of the filenames contain spaces.

Web.config

<appSettings>
  <add key="UploadDirectory" value="~/Upload/"/>
</appSettings>

FileBrowser.aspx.cs

public partial class FileBrowser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {        
        DirectoryInfo di = new DirectoryInfo(Request.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadDirectory"]));
        if (Directory.Exists(di.ToString()))
            printDir("", di.ToString());

    }

    protected void printDir(string space, string dir)
    {
        DirectoryInfo di = new DirectoryInfo(dir);
        foreach (DirectoryInfo d in di.GetDirectories())
        {
            Response.Write(space + "<a href=" + d.ToString() + ">" + d.ToString() + "</a><br/>");
            printDir(space + "&nbsp;&nbsp;&nbsp;&nbsp;", dir + "\\" + d.ToString());
        }

        foreach (FileInfo d in di.GetFiles())
        {
            Response.Write(space + "<a href=" + "Upload/" + d.Name + ">" + d.FullName + "</a><br/>");
        }
    }
}

Solution

  • The problem is that when rendering the path for the files in the subfolders, you're using the path like "Upload/filename"; this is not correct.

    In fact, you should try to get the directory names from the current di variable. That is, if you're currently browsing "Inner" folder inside the "Upload" folder, your path would be something like "Upload/Inner/filename".

    This is where you need to make changes:

      Response.Write(space + "<a href=" + "Upload/" + d.Name + ">" + d.FullName + "</a><br/>");
    

    In the above code line, you need to create the href URL dynamically depending upon the path in di variable. Do the following:

    1. Get di path
    2. Get the substring after "\Upload" in the di path
    3. Split the above substring by "\"; this will give you any subdirectoryies.
    4. Make a new path to the file using above subdirectories.

    I hope this helps.