How to use Server.MapPath to get location outside website folder in ASP.NET

前端 未结 4 1655
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 10:53

When my ASP.NET site uses documents (e.g. XML), I normally load the document as follows:

Server.MapPath(\"~\\Documents\\MyDocument.xml\")

H

4条回答
  •  执笔经年
    2020-12-06 11:31

    If you know where it is relative to your web root, you can use Server.MapPath to get the physical location of your web root, and then Path class's method to get your document path.

    In rough unchecked code something like:

    webRootPath = Server.MapPath("~")
    docPath = Path.GetFullPath(Path.Combine(rootPath, "../Documents/MyDocument.xml"))
    

    Sorry if I got the Syntax wrong, but the Path class should be what you are after to play with real FS paths rather than the web type paths.

    The reason your method failed is that Server.MapPath takes a location on your web server and the one you gave is not valid, since it is "above" the top of the root of the server hierarchy.

提交回复
热议问题