Server.MapPath to go two folder back from root

后端 未结 5 1090
鱼传尺愫
鱼传尺愫 2020-12-30 12:12

Here is how I do it:

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

HI know that \'.\' is for the root of the project, but how

相关标签:
5条回答
  • 2020-12-30 12:25

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

    You can't go back above site root because of security restrictions, see also this article from other solutions.

    IIS purposefully prevents serving up content directly that is outside of the site path. However, you can create a virtual directory in IIS and have ISAPI Rewrite point to that. For example, create a virtual directory called /staticfiles that points to c:\test\data\static-files. As far as IIS is concerned, that's directly off of the root of the site in a folder called /staticfiles.

    0 讨论(0)
  • 2020-12-30 12:30

    You can use Parent.Parent.FullName

      string grandParent  = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/")).Parent.Parent.FullName;
    
    0 讨论(0)
  • 2020-12-30 12:35

    Easiest way, you can still use the following:

    string MyFolderName = Server.MapPath("~/AliasName/");
    

    Add a Virtual Directory to your application. Here's how:

    • In Visual Studio under your root folder right click:
    • Add > New Virtual Directory
    • Alias name: AliasName
    • Folder: click on > Browse...
    • Navigate to the folder you need and done.

    That's it, now you have access!

    0 讨论(0)
  • 2020-12-30 12:36

    Since you are using MapPath you are getting returned a physical path(\) from a virtual path(/).

    Creating a DirectoryInfo object or using a Path utility method starting from your child app root won't necessarily give you what you expect unless your virtual parent and virtual grandparent have the same hierarchy as your physical directory structure.

    My apps are not physically nested to match the Url depth. This could also be the case if a virtual directory is involved.

    Assuming a grandparent app is two virtual folders up this would get you the physical path...

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

    Using this would keep you safe from any virtual directory shuffle games going on in the IIS setup.

    I used this to see how far I could go up. I did not get an HttpException until I tried to go above wwwroot.

    0 讨论(0)
  • 2020-12-30 12:39

    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 app very likely won't have permission to read or write there - I'm not sure what you're going to do with it.

    0 讨论(0)
提交回复
热议问题