0

I'm trying to find a root folder on the server. Nothing works, or works wrong

@{
        string [] list = Directory.GetFiles(Directory.GetCurrentDirectory());
        foreach(var item in list)
        {
            <p>@item</p>   
        }
    }

Shows exactly what I don't need

@{
        string [] list = Directory.GetFiles("~/");
        foreach(var item in list)
        {
            <p>@item</p>   
        }

}

Doesn't work

How to solve this?

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
user3493623
  • 91
  • 4
  • 12
  • I think that you are a little be confused.GetFiles method return some stuff alias string array of all files within a directory.What is your goal??? – makemoney2010 Apr 30 '14 at 12:02
  • possible duplicate of [How do I get the root directory of my ASP.NET server application?](http://stackoverflow.com/questions/17682843/how-do-i-get-the-root-directory-of-my-asp-net-server-application) – captainsac Jun 22 '15 at 06:41

3 Answers3

2

You can use the following:

Server.MapPath("~");

The ~ is always the root in an ASP.NET application. If you insert it in a Razor view it will be translated to the appropriate path for "external access", e.g. ~/Content/site.css will be converted to /Content/site.css if the site is hosted in the root directory or to e.g. /Page1/Content/site.css if it is hosted at a virtual directory called Page1. Therefor to get the absolute path you need to "map it".

If you do not have access to Server you can also use HostingEnvironment.ApplicationPhysicalPath.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
1

Try

Server.MapPath("~");

or:

HostingEnvironment.ApplicationPhysicalPath 
captainsac
  • 2,484
  • 3
  • 27
  • 48
0

Refer http://msdn.microsoft.com/en-us/library/ms178116.aspx. For your ease i have modified your code:

string [] list = Directory.GetFiles(Server.MapPath("~"));
        StringBuilder sb=new StringBuilder();
        foreach (var item in list)
        {
            sb.Append(item + "\n");
        }

        Response.Write(sb);

Even though I am giving you answer, I will suggest try to have path which is configurable in web.config or in the database because fixing paths are like hard coding the login ID :). Hope you got me.

Thanks

mannu2050
  • 403
  • 3
  • 11