Server.MapPath to return two folders from the root

Here is how I do it:

HttpContext.Current.Server.MapPath(@"~\~\~\Content\") 

I know that '.' for the root of the project, but how to return multiple folders?

+6
source share
4 answers

If you really need the grandparent path, you can get it from the root path using Path.GetDirectoryName() :

 string root = Server.MapPath("~"); string parent = Path.GetDirectoryName(root); string grandParent = Path.GetDirectoryName(parent); 

But your web application will most likely not have permission to read or write there - I'm not sure what you are going to do with it.

+9
source

Start at the root of your site with ~ and specify the full path: ~/Archive/Content .

You cannot return above the root of the site due to security restrictions; see also this article from other solutions.

IIS deliberately prevents the direct serving of content that is outside the site path. However, you can create a virtual directory in IIS and specify an ISAPI rewrite point. For example, create a virtual directory / staticfiles that points to c: \ test \ data \ static-files. As for IIS, this is directly from the root of the site in a folder named / staticfiles.

+3
source

You can use Parent.Parent.FullName

  string grandParent = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/")).Parent.Parent.FullName; 
+3
source

Since you are using MapPath, you are returning the physical path (\) from the virtual path (/).

Creating a DirectoryInfo object or using the Path utility method starting with your child application root will not necessarily give you what you expect if your virtual parent and virtual grandparents do not have the same hierarchy as your physical directory structure.

My applications are not physically nested according to the depth of Url. This can also occur if a virtual directory is involved.

Assuming the grandparent application is two virtual folders, you get the physical path ...

  string physicalGrandparentPath = HttpContext.Current.Server.MapPath("~/../../"); 

Using this, you will be protected from any virtual games that will be moved in IIS settings.

I used this to understand how far I can go. I did not get an HttpException until I tried to go above wwwroot.

0
source

Source: https://habr.com/ru/post/910836/


All Articles