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

霸气de小男生 提交于 2019-11-27 23:40:38
Chris

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.

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

AppDomain.BaseDirectory returns current web application assembly directory path.

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;
    }
}

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

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