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

倖福魔咒の 提交于 2019-11-26 21:34:05

问题


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

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

However, I would like to move the Documents folder out of the website folder so that it is now a sibling of the website folder. This will make maintaining the documents considerably easier.

However, rewriting the document load code as follows:

Server.MapPath("../../Documents/MyDocument.xml")

results in a complaint from ASP.NET that it cannot 'exit above the top directory'.

So can anyone suggest how I can relatively specify the location of a folder outside the website folder? I really don't want to specify absolute paths for the obvious deployment reasons.

Thanks

David


回答1:


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.




回答2:


docPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\Documents\MyDocument.xml");

AppDomain.BaseDirectory returns current web application assembly directory path.




回答3:


If you need to resolve the path in either case absolute or relative (even outside the web app root folder) use this:

public static class WebExtesions
{
    public static string ResolveServerPath(this HttpContextBase context, string path) {
        bool isAbsolute = System.IO.Path.IsPathRooted(path);
        string root = context.Server.MapPath("~");
        string absolutePath = isAbsolute ? 
                                    path : 
                                    Path.GetFullPath(Path.Combine(root, path));
        return absolutePath;
    }
}



回答4:


If you want to specify the Location somewhere in harddrive , then its is not easily available on web environment. If files are smaller in size and quantity then you can keep it inside directory and point then using ~/path till directory.

But in some cases we used to do Request object. For more visit this link

http://msdn.microsoft.com/en-us/library/5d5940ad.aspx



来源:https://stackoverflow.com/questions/3422270/how-to-use-server-mappath-to-get-location-outside-website-folder-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!